I am working on a project and I want to insert into 2 different tables, so I wrote those 2 queries (query1, query2), when i run the program with just one query i don't get any exceptions but when executing together i have a bunch of exceptions, i used preparedStatement execute() and didn't work
note : im not very experienced please explain easily
private void loadBusesToDB() throws SQLException{
Connection connection = connect();
String query = "INSERT INTO Bus (nomLigne, Marque, Matricule, Capacite)"
+ "VALUES (?, ?, ?, ?)";
String query2 = "INSERT INTO Lignes (nomLigne, Sntv Depart, SNTV Arrive, prix)"
+ "VALUES (?, ?, ?, ?)";
PreparedStatement ps = null;
PreparedStatement ps2 = null;
try {
ps = connection.prepareStatement(query);
ps2 = connection.prepareStatement(query2);
for(Bus bus : Bus.buses){
ps.setString(1, bus.getNomLigne());
ps.setString(2, bus.getMarque());
ps.setString(3, bus.getMatricule());
ps.setInt(4, bus.getCapacite());
ps.addBatch(); // THE INSERT HAPPENS HERE
}
ps.executeBatch();
for(Lignes ligne : Lignes.lignes){
ps2.setString(1, ligne.getNomLigne());
ps2.setString(2, ligne.getDepart());
ps2.setString(3, ligne.getArrive());
ps2.setFloat(4, ligne.getPrix());
ps2.addBatch(); // THE INSERT HAPPENS HERE
}
ps2.executeBatch();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("ERROR HERE");
throw ex;
}finally{
ps.close();
ps2.close();
connection.close();
}
}
Error:
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.2 user lacks privilege or object not found: SNTV
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:509)
at sntv.MainMenuController.loadBusesToDB(MainMenuController.java:135)
at sntv.MainMenuController.initialize(MainMenuController.java:277)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
As #uaraven points out, you have a syntax error regarding column names in the second query. In SQL, any identifier (including table, column, stored procedures, functions, etc.) with spaces or special characters/symbols in their names or names match reserved words need to be escaped when referenced in any clause (SELECT,FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY ).
Now, different RDBMS's handle such escaping differently. Consider the following depending on your database. SQLite may be the only RDBMS that includes all.
Double Quotes (ANSI-SQL standard) (Oracle, DB2, Postgres, RedShift, Teradata, SQLite, with added rules of capitalization for some; SQL Server/MySQL does support with mode changes)
String query2 = "INSERT INTO Lignes (nomLigne, \"SNTV DEPART\", \"SNTV ARRIVE\", prix)"
+ " VALUES (?, ?, ?, ?)";
Square Brackets (SQL Server, Sybase, SQLite, MS Access)
String query2 = "INSERT INTO Lignes (nomLigne, [Sntv Depart], [SNTV Arrive], prix)"
+ " VALUES (?, ?, ?, ?)";
Backticks (MySQL, MariaDB, Google BigQuery Standard SQL, SQLite, MS Access)
String query2 = "INSERT INTO Lignes (nomLigne, `Sntv Depart`, `SNTV Arrive`, prix)"
+ " VALUES (?, ?, ?, ?)";
Related
I want to insert 5 datas into one SQL table, the last four of which are already working and fine, but the first one should be from another table, a String, giving an Int to the table in which im inserting it. And this is my solution so far. However i'm still getting an error:
"The index 5 is out of range."
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1,1);
stmt.setInt(2, recid);
stmt.setInt(3, inputData);
stmt.setDate(4, sqlDate);
stmt.setTime(5, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
Actually you have only four parameters defined on your query, because LocationId is being calculated by the inner select you provided. That's why you are getting the error.
Try this:
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1, recid);
stmt.setInt(2, inputData);
stmt.setDate(3, sqlDate);
stmt.setTime(4, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
I'm having trouble inserting a row into a MySQL table with Java. I'm not sure what the problem is as it isn't giving an error. I'm trying to insert the row with the following:
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?);";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
The table 'users' is created successfully with no errors with the following:
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (uuid VARCHAR(40), authKey VARCHAR(30), code INT(10), scratches VARCHAR(45));");
When trying to insert the row with the same update in phpmyadmin, it works fine. There is no error given by the update so I have no idea where to start debugging. Any help would be appreciated. Thanks.
You have to do commit transaction check the below code
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
connection.commit();
I'm currently facing a problem with my SQL query using a prepared statement.
String test= "INSERT INTO TEST" + "(ID, IC, CN, CT, Time)"
+ "VALUES ('"+ ID +"','"+ IC +"','"+CN +"','"+ CT +"','"+ time +"')";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.executeUpdate();
I have successfully connected to the database, and the table is created out. Is it because of the single quotation problem?
You're missing the point of using a PreparedStatement. You could just bind the values so you don't have to mess around with quoting yourself:
String test= "INSERT INTO TEST (ID, IC, CN, CT, Time) VALUES (?, ?, ?, ?, ?)";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.setString(id);
preparedStatement.setString(ic);
preparedStatement.setString(cn);
preparedStatement.setString(ct);
preparedStatement.setDate(new Timestamp(time));
preparedStatement.executeUpdate();
Hi I am trying insert data into the database using prepared statement but I am getting syntax error could u please help
public boolean SignUp(String last_name, String first_name,String email, String password,String confirm_password,String phone){
Connect connect = new Connect();
Connection conn = connect.Connection();
java.sql.PreparedStatement preparedStatement = null;
//NULL is the column for auto increment
String insertQuery = "INSERT INTO users VALUES (NULL, ?, ?, ?, ?, ?, ?)";
preparedStatement = conn.prepareStatement(insertQuery);
preparedStatement.setString(1, last_name);
preparedStatement.setString(2, first_name);
preparedStatement.setString(3, email);
preparedStatement.setString(4, password);
preparedStatement.setString(5, confirm_password);
preparedStatement.setString(6, phone);
int rs = preparedStatement.executeUpdate(insertQuery);
conn.close();
}
here is the error message
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?)' at line 1
I found the answer :)
Use preparedStatement.execute() instead of executeUpdate(sql). You have already set the sql and params - the new setting in executeUpdate(sql) overrides the bind.
You should change the statement to list the columns explicitly, and drop NULL from the list of values.
String insertQuery = "INSERT INTO users"
+ " (last_name, first_name, email, password, confirm_password, phone)"
+ " VALUES(?,?,?,?,?,?)";
This way your insert statement is no longer dependent on the order of columns in your users table, and is also immune to addition of columns to the table.
Note that although this design is probably OK for a toy or an education system, but in a real production system storing password in a table is very dangerous. Storing confirm_password is rather unusual, too: normally your system checks that password is the same as confirm_password, and then inserts a salted password hash and a salt into the table.
Just a guess, not I'm not certain. But if one of the fields is autoincrement, then I don't think you need to insert it. Try taking out that NULL....
I get an error when I try to insert some rows to a db. so here is the code
try {
String insertStmt = "INSERT into " +
"MY_TABLE('RECORD_TYPE', 'FILE_TYPE', 'DATE', 'BATCH_NO', 'RECORD_COUNT')" +
"VALUES(?, ?, ?, ?, ?);";
PreparedStatement pstmt = super.con.prepareStatement(insertStmt);
pstmt.setString(1, input[0]);
pstmt.setString(2, input[1]);
pstmt.setString(3, input[2]);
pstmt.setString(4, input[3]);
pstmt.setString(5, input[4]);
System.out.println("Insert rows : " + pstmt.executeUpdate());
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
sqle.printStackTrace();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
con.close();
}
and everything on the db is of varchar type, double checked the columns (they all are the same name), took out the quotes off the column name (same result) no success. to add it up, the error message is not very helpful.
any suggestions would be appreciated.
You need to change the SQL statement. (Never use reserved words as identifiers)
String insertStmt = "INSERT into \"MY_TABLE\" (RECORD_TYPE,FILE_TYPE,
\"DATE\",BATCH_NO,RECORD_COUNT) VALUES (?, ?, ?, ?, ?)";
Use " (double quotes) to escape the reserved words/keywords.
I can spot two problems:
No need for single quotes around column names. But you may wrap it in double quotes. It is necessary if you are using reserved keywords for column names or table names. Here DATE.
You need a space before VALUES.
So you need to change insertStmt to somthing like this:
String insertStmt = "INSERT into " +
"MY_TABLE(RECORD_TYPE, FILE_TYPE, \"DATE\", BATCH_NO, RECORD_COUNT) " +
"VALUES(?, ?, ?, ?, ?);";
Print insertStmt String in Console and try to fire it in directly backend. It gives you exact error in backend. It seens some spacing or syntax error.
I just came to this page while searching for ORA-00928, and I'd like to note that my problem was an extra comma at the start of the column list:
INSERT INTO redacted.redacted
(
, redacted_id -- The comma at the start of this line will trigger ORA-00928.
, another_redacted_id
, redacted1
, redacted2
, redacted3
, created_at
, created_by
, changed_at
, changed_by
)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)
For others searching for the same error: Other syntactical issues with the query can cause the same exception to be thrown. For example, omitting the word VALUES.
I was running the same issue, and in my case the query was like this:
insert into Address (number, street, id) values (?, ?, ?)
The problem was caused by the number column name since number is a reserved keyword in Oracle, and the exception was sort of misleading ORA-00928: missing SELECT keyword.
After escaping the number column, the statement was executed normally:
insert into Address ("number", street, id) values (?, ?, ?)