I am trying to insert into a vehicle table using a prepared statement. This is the table shown in PHPMyAdmin.
This is my java code
try {
String sql = "INSERT INTO vehicle (vin, serial, make, model, year, reg.no., status) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, vin);
statement.setString(2, serial);
statement.setString(3, make);
statement.setString(4, model);
statement.setInt(5, 10);
statement.setInt(6, 17);
statement.setString(7, status);
System.out.println(statement.toString());
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
} catch (Exception ex) {
System.out.println(ex);
}
and this is the resulting error
com.mysql.jdbc.exceptions.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 ' status) VALUES ('dfg', 'dfgfg', 'fg', 'sd564', 10, 17, 'dsf')' at line 1
I am clueless. Does it have to do with me not passing a value for the primary key "id" column in the table?
reg.no. isn't a valid column name. If you really need to use it, you should quote it:
INSERT INTO vehicle (vin, serial, make, model, year, `reg.no.`, status)
-- Here ---------------------------------------------^-------^
VALUES (?, ?, ?, ?, ?, ?, ?)";
Related
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.
String sql = " INSERT INTO `tblservice` (`ServiceID`,`accountID`, `Kind`, `Description`, `Price`, "
+ "`Quantity`, `Total`, `DateAndTime`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, this.accountID);
pstm.setString(2, "" + SelectionBox.getSelectedItem());
pstm.setString(3, desc);
pstm.setFloat(4, Float.parseFloat(PriceTF.getText()));
pstm.setFloat(5, Float.parseFloat(QuantityTF.getText()));
pstm.setFloat(6, this.getTotal());
pstm.setDate(7, dateAdded);
pstm.executeUpdate();
Error
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 '?, ?, ?, ?, ?, ?, ?)' at line 1
Instead of make NULL in your query VALUES (NULL, ...) use setNull for example :
pstm.setNull(1, java.sql.Types.INTEGER);
It will take the type, of your field, in this example i consider it is a java.sql.Types.INTEGER it can be java.sql.Types.VARCHAR or any sql type
So your query should be like this :
String sql = "INSERT INTO tblservice (ServiceID, accountID, Kind, Description,
Price, Quantity, Total, DateAndTime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setNull(1, java.sql.Types.INTEGER);
pstm.setInt(2, this.accountID);
....
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
public boolean setgame(int botid, int gameid, String name, String ip, int spoofed, int reserved, int loadingtime, int left, String leftreason, int team, int colour, String spoofedrealm) {
try {
Connection connection = connection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO gameplayers (id, botid, gameid, name, ip, spoofed, reserved, loadingtime, left, leftreason, team, colour, spoofedrealm) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
statement.setInt(1, botid);
statement.setInt(2, gameid);
statement.setString(3, name);
statement.setString(4, ip);
statement.setInt(5, spoofed);
statement.setInt(6, reserved);
statement.setInt(7, loadingtime);
statement.setInt(8, left);
statement.setString(9, leftreason);
statement.setInt(10, team);
statement.setInt(11, colour);
statement.setString(12, spoofedrealm);
statement.execute();
connectionReady(connection);
return true;
} catch (SQLException e) {
if (Main.DEBUG) {
}
Main.println("[SQLThread] Unable to add bot ban to MySQL database: " + e.getLocalizedMessage());
}
return false;
}
I created a main method to add all data and I can't see any error in the insert statement.
I am getting this error:
[SQLThread] Fail: 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 'left, leftreason, team, colour, spoofedrealm) VALUES (NULL, 2, 146, 'Teste', '120.32' at line 1
LEFT is reserved word in MySql (as in LEFT OUTER JOIN...). You need to use quotes around it to use it as an identifier.
Better yet, consider renaming the field to not use a reserved word as an identifier.
LEFT is a reserved word in MySQL; you have to escape it:
INSERT INTO gameplayers (
id, botid, gameid, name, ip, spoofed, reserved, loadingtime, `left`, ...
----------^----^
I am learning MySQL with JAVA, and don't understand prepared statements. Abstracting from I shall learn it, I want to ask for help in finishing this code to be "prepared stated" :-)
String stringQuery = "INSERT INTO banlist (name, reason, admin, time, temptime, IP) VALUES (testNick, testPowod, testAdmin, CURRENT_TIMESTAMP, NOW(), NULL);=?";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString( 1, ); // after ' 1, ' we define what we want to get
ResultSet resultSet = statement.executeUpdate();
String stringQuery =
"INSERT INTO banlist (name, reason, admin, time, temptime, IP)"
+ " VALUES (?, ?, ?, CURRENT_TIMESTAMP, NOW(), NULL)";
PreparedStatement statement = this.connection.prepareStatement(stringQuery);
statement.setString(1, testNick);
statement.setString(2, testPowod);
statement.setString(3, testAdmin);
int inserted = statement.executeUpdate();
Read the JDBC tutorial.
Here's how I'd do it:
String insertQuery = "INSERT INTO banlist(name, reason, admin, time, temptime, IP) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString(1, name); // These values come from your code; dynamic
statement.setString(2, reason);
statement.setString(3, admin);
statement.setString(4, time);
statement.setString(5, tempTime);
statement.setString(6, ip);
int numRowsAffected = statement.executeUpdate();
Be sure to close your statement appropriately.