Error in SQL syntax using Java - java

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`, ...
----------^----^

Related

Oracle primary key generator in Java

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.

JDBC Prepared Statement Syntax Error

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

SQL Syntax error near ' 'x')' at line 1 (Insert statement)

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

PreparedStatement not putting arguments [duplicate]

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.

java.sql.SQLException: ORA-00928: missing SELECT keyword. when inserting record to DB using JDBC

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

Categories

Resources