Ilya Kulikov Ilya Kulikov - 21 days ago 7
SQL Question

Inserting Error

i'm trying to insert in postgresql db date, but when i'm insterting it, i'm getting this error:


Error occurred while INSTERING Operation: org.postgresql.util.PSQLException: ERROR: column "text that i wrote" does not exist"


I don't understand what did i code wrong that, program tries to find culumn in values.

But when i try to output this table, it outputs without errors

WORKERDAO class

public static void insertWrk(String name, String post) throws SQLException, ClassNotFoundException {
//Declare a INSTERT statement
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
//Execute INSTERT operation
try {
DBUtil.dbExecuteUpdate(updateStmt);
} catch (SQLException e) {
System.out.print("Error occurred while INSTERING Operation: " + e);
throw e;
}
}


DBUTIL class

public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
//Declare statement as null
Statement stmt = null;
try {
//Connect to DB
dbConnect();
//Create Statement
stmt = conn.createStatement();
//Run executeUpdate operation with given sql statement
stmt.executeUpdate(sqlStmt);
} catch (SQLException e) {
System.out.println("Проблема в выполнение executeUpdate операции : " + e);
throw e;
} finally {
if (stmt != null) {
//Close statement
stmt.close();
}
//Close connection
dbDisconnect();
}
}


WorkerController Class

@FXML
private void insertWorker (ActionEvent actionEvent) throws SQLException, ClassNotFoundException {
try {
WorkerDAO.insertWrk(nameText.getText(),postCombo.getSelectionModel().getSelectedItem());
} catch (SQLException e) {
System.out.println("Problem occurred while inserting worker " + e);
throw e;
}
}

Answer

You need to put quotes around the data you're inserting:

String updateStmt ="INSERT INTO worker(full_name,post)" +
                        "VALUES" +
                        "("+name+","+post+");";

Should be:

String updateStmt ="INSERT INTO worker(full_name,post)" +
                        "VALUES" +
                        "('"+name+"',"'+post+'");";

Be aware that you're risking SQL Injection attacks using this method, see about using a parameterised insert. This site lists a bit more detail.