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();
Related
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 (?, ?, ?, ?)";
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 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();
I am new to java and trying to learn to insert the username and password and a profile image path into a Mysql database. When I run the following code, it will insert into table but the path filed of the table 'table_profile' 3rd column like as follows
if path equals "C:/Users/Manohar/Documents/FileUplaodDemo/build/web/uploads/x.jpg"
then it is inseerted as path equals "C:UsersManoharDocumentsFileUplaodDemo uildwebuploads
stmt = connection.prepareStatement(
"insert into table_profile values('"+userId+"','"+userName+"','"+path+"')");
User parameter binding like this:
stmt = connection.prepareStatement("insert into table_profile values(?, ?, ?)");
stmt.setInt(1, userId);
stmt.setString(2, userName);
stmt.setString(3, path);
Let Java do all the hard work for you :)
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....