Syntax error in Prepared statement while inserting into db - java

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....

Related

how to execute 2 queries together?

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 (?, ?, ?, ?)";

MySQL INSERT INTO doesn't work but gives no error

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();

Prepared statement for SQL query, error DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703

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();

Java problemDatabase Syntax Error at or near ":"

Im using a PostgreSQL database, and when i'm trying to insert the data, it gives me an error problemDatabase error: ERROR syntax error at or near ":" Position 206.
Here is a code for insert query :
public static Model_Customer Insert(String FName, String LName, String Registration, String Make, String Model, String Engine, String Year, String Mileage, String Type, String Date, String Time) throws Exception {
try{
Statement stmt = Model_Customer.conn.createStatement();
ResultSet rs = stmt.executeQuery("INSERT INTO appointment (fname, lname, registration, make, model, engine, year, mileage, type, date, time) VALUES ("+FName+",'"+LName+"','"+Registration+"','"+Make+"','"+Model+"','"+Engine+"','"+Year+"','"+Mileage+"','"+Type+"','"+Date+"',"+Time+") RETURNING appointmentid");
if(rs.next())
return Model_Customer.QueryID(rs.getInt(1));
}catch(Exception e){
throw new Database_Exception(e.getMessage());
}
return null;
}
In Debug it goes okay to the executeQuery and straight after it, it goes to the catch exception and gives an error. Table and columns in the database are there. There's no ":" anywhere in the code except the messages, so im not sure why it goes like this.
Thanks for your answer Joop Eggen I have used you way and had to add
stmt.executeUpdate();
Worked like a charm! Thanks!
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO appointment (fname, lname, registration, make, model, "
+ "engine, year, mileage, type, \"date\", \"time\") "
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, FName);
stmt.setString(2, LName);
stmt.setString(3, Registration);
...
int updateCount = stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next())
return Model_Customer.QueryID(rs.getInt(1));
JDBC offers a database engine independent way to retrieve the generated keys: a result set of inserted rows with the generated keys per row.
RETURN_GENERATED_KEYS is probably not needed. Some field names might be reserved key words, which then need double quotes around them.
About recommending PreparedStatement:
The first remark on every ...+var+... construed statement, will be: use a prepared statement with ... ? .... There are two very important reasons (besides the efficiency of a PreparedStatemen and using BLOBs):
SQL injection, see this;
you can leave out the apostrophes ('), and escaping of apostrophe, backslash etcetera is done for you, and you can pass typesafe parameters (int, java.sql.Date).

Inserting value into table in java

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 :)

Categories

Resources