This question already has answers here:
Syntax error in WHERE clause near '?) AND (Date = ?)'
(2 answers)
Closed 8 years ago.
I am having problems running this code using PreparedStatement on my MySQL server. It has been doing np before, when I had a standart Statement included. Mind: this is a test program, I am only learning this stuff. The code is:
PreparedStatement st = null;
try {
int id = registry.newID("ID");
if (id == 0) {
out.println("Failed to generate a new ID. Terminating dialogue.");
return;
}
String insert = "INSERT INTO registry (ID, NAME, SURNAME, DATE_OF_BIRTH, CITY, STREET) "
+ "VALUES (?, ?, ?, ?, ?, ?);";
st = registry.getConn().prepareStatement(insert);
st.setInt(1, id);
st.setString(2, name);
st.setString(3, surname);
st.setDate(4, date);
st.setString(5, city);
st.setString(6, street);
st.executeUpdate(insert);
registry.getConn().commit();
out.println("Added. Add a number? [y/n] ");
char choice = in.next().charAt(0);
if (choice == 'y') {
addNumber(id, registry);
}
st.close();
} catch (SQLException ex) {
out.println("SQL Exception: " + ex);
}
with params being the following:
int id;
String name, surname, city, street;
java.sql.Date date;
This gives me the following exception:
SQL Exception: 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
Why aren't the values set in the st.setXXXX statements?
Thanks
Here's the problem:
st.executeUpdate(insert);
So, instead of PreparedStatement.executeUpdate you call Statement.executeUpdate(String sql) and pass insert statement with question marks.
Try to change this line to:
st.executeUpdate();
The problem is with SQL syntax. I suspect the semicolon at the end of the SQL statement. It does not belong there - you probably copied it form some other tool where you tested your query.
Related
I'm trying to update the values of a table, but it throws an error that I have not been able to determine. If you visualize it it would help me, this is what it throws by console:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'name='Proyecto ' status=0 language='PHP' duration=16 advance=16 effec=0.0 where ' at line 1
public int actualizar(Proyecto p, int pos) {
String sql = "UPDATE proyecto SET code=? name=? status=? language=? duration=? advance=? effec=? where code='"+ pos +"' " ;
try {
con = conectar.getConexionSQL();
ps=con.prepareStatement(sql);
ps.setInt(1, p.getCod());
ps.setString(2, p.getNombre());
ps.setInt(3, p.getStatus());
ps.setString(4, "PHP");
ps.setInt(5, p.getDuracion());
ps.setInt(6, p.getAvance());
ps.setDouble(7, 0.0);
ps.executeUpdate();
return 1;
} catch(Exception e){
e.printStackTrace();
}
return 1;
}
Assignments in the SET must be separated by commas:
UPDATE proyecto
SET code = ?, name = ?, status = ?, language = ?, duration = ?, advance = ?, effec=?
WHERE code = ?
Possibly unrelated note: do you really mean to update column code, which you are using to identify which record(s) should be updated? Although this is valid SQL, this might not really make sense from functional perspective.
My app allows users to create an account (stored in database) and place orders.
When a client registers himself, I want to generate a primary key named CLIENT_CODE to identify him, starting from x value and increment it with y value. (I'm using oracle 11g atm)
I've tried this so far:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String fname = jTextField9.getText();
String lname = jTextField10.getText();
String city = jTextField11.getText();
String street = jTextField13.getText();
String number = jTextField14.getText();
String userClient = jTextField15.getText();
String pass1 = String.valueOf(jPasswordField5.getPassword());
String pass2 = String.valueOf(jPasswordField6.getPassword());
if(verifyFields()){
if(!checkUsername(userClient)){
OraclePreparedStatement ps;
OracleResultSet rs;
String registerClient = "insert into CLIENT (FNAME_CL, LNAME, CITY, STREET, NUMBER, MONEY, CLIENT_CODE, USER_CLIENT, PASS) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = (OraclePreparedStatement) JavaConnectDb.ConnectDb().prepareStatement(registerClient);
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, city);
ps.setString(4, street);
ps.setString(5, number);
ps.setDouble(6, 0.0);
ps.setInt(7, ???); <--- here should be the generated primary key
ps.setString(8, userClient);
ps.setString(9, pass1);
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null, "Account created!");
} else{
JOptionPane.showMessageDialog(null, "Error: Check your info");
}
} catch (SQLException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Don't do it in Java; handle the primary key value creation in the database using a sequence:
CREATE SEQUENCE CLIENT__CLIENT_CODE__SEQ
START WITH 1
INCREMENT BY 1
Then just use your sequence in the INSERT statement and use the RETURNING clause to get the generated value as an OUT parameter of your prepared statement.
insert into CLIENT (
FNAME_CL,
LNAME,
CITY,
STREET,
NUMBER,
MONEY,
CLIENT_CODE,
USER_CLIENT,
PASS
) values (
?,
?,
?,
?,
?,
?,
CLIENT__CLIENT_CODE__SEQ.NEXTVAL,
?,
?
) RETURNING CLIENT_CODE INTO ?
If you were using Oracle 12c then you could use GENERATED AS IDENTITY in the table's CREATE DDL statement to generate the values without creating a separate sequence.
I am writing a program for practice that allows me to edit a database. I have it so that it loads and displays the data and I have it so that it can add entry's. I am now having issues with deleting an entry, my code is below, and when I run it I get an error that says:org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "(": syntax error), I have looked through the code and I don't see any errors.
#FXML
private void selectStudent(ActionEvent event) throws SQLException{
StudentData stud = studenttable.getSelectionModel().getSelectedItem();
String sqlRemove = "DELETE FROM Students(id, fname, lname, email, dob) VALUES (?, ?, ?, ?, ?)";
try {
if (stud != null) {
Connection conn = dbConnection.getConnection();
PreparedStatement st = conn.prepareStatement(sqlRemove);
st.setString(1, this.idcolumn.getText());
st.setString(2, this.fnamecolumn.getText());
st.setString(3, this.lnamecolumn.getText());
st.setString(4, this.emailcolumn.getText());
st.setString(5, this.dobcolumn.getText());
st.execute();
conn.close();
} else {
test.setText("Please select an Entry");
}
}catch (Exception ex){
ex.printStackTrace();
}
}
DELETE FROM Students(id, fname, lname, email, dob) VALUES (?, ?, ?, ?, ?)
is Not a valid Delete query , Try to run the same in sqlLite you will get to know.
It should be DELETE FROM Students where (pass any of one condition which returns a row value) i.e. id=?
I'm getting problems trying to run this simple sql statement.
try{
stm.executeUpdate("INSERT INTO exam_somatique_6_12(id_p, id_m, id_u, Date, age, poids, taille, TA, exam_clinique, acuite_visuelle, acuite_auditive, age_puberte, conclusion) VALUES ("+idpat+","+idmed+","+idum+",'"+currentdate+"',"+txtage.getText()+","+txtpoids.getText()+","+txttaille.getText()+","+txtta.getText()+",'"+Clinique+"','"+Visuelle+"', '"+Auditive+"', "+Signe+", '"+txtobservation.getText()+"')");
}
catch(SQLException e1)
{
System.err.println(e1.getMessage());
}
dispose();
I have no problem when executing it on mysql, but as soon as I try to do it in Java, I get this message error :
syntax error near ' 'x')' at line 1
And x is the result of the txtobservation.getText().
Also, I'm pretty sure it's not a quote problem, I'm using ' ' when it's a text, and not doing it when it's an integer.
Thanks for your help.
You have to use PreparedStatement instead it is more secure and more helpful
String query = "INSERT INTO table(id_p, id_m, id_u, Date, age, poids, taille,
TA, clinique, visuelle, auditive, puberte, observation)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement ps = connection.prepareStatement(query) {
ps.setInt(1, idpat);//set values to your query
ps.setInt(2, idmed);
....
ps.executeUpdate();//execute your query
}
Note
getText it return String and not int and not float if txtage.getText() is int you have to convert it to int you can use :
Integer.parseInt(txtage.getText());//get int value form a String
Float.parseFloat(txtpoids.getText());//get float value from a String
and so on
I'm using a UI that I've built to get input and MySQL to store the data locally. However, when I use the MySQL insert function, I'm encountering the following error:
java.sql.SQLException: No value specified for parameter 5
I only have four input fields, and four columns in the table; however, my debugger says I have seven value parameters. Here is the Insert statement:
private static final String GLInsert = "INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
And the preparedStatement method:
public void InsertGL(String ANstr, String ANAstr, String AIstr, double balfor) {
try {
conn = DriverManager.getConnection(ConnCheck, user, password);
GL_List = FXCollections.observableArrayList();
st = conn.prepareStatement(GLInsert);
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
st.executeUpdate();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(GLMaintAcct.class.getName()).log(Level.SEVERE, null, ex);
}
}
The issue is you have 7 parameters according to this query:
"INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
But you have just 4 value assigned like below:
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
You should add other 3 values like this providing their types:
st.setString(5, value5);
st.setDouble(6, value6);
st.setString(7, value7);