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

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

Related

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

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

Unable to insert a row in Oracle with Java (JDBC) --> error ORA-00917: missing comma

I have a problem during an insert in Oracle using Java and JDBC. The error obtained is:
java.sql.SQLException: ORA-00917: missing comma
The data for the insert is taken from a form like a string and is parsed to the appropiated data type and then is saved in an object called edicio. That's all OK. Then, my intention is make an insert in the DB using the data of this object.
Here is the code of the DAO, where I'm making the insert:
public Edicio insertarCurs(Connection con, Edicio ed) throws SQLException {
PreparedStatement stm = null;
ResultSet rst = null;
// Insert
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO curs (id, nom, idarea, area, programa, datainici)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
logger.info("Building insert works fine.");
try {
stm = con.prepareStatement(sql.toString());
// params
stm.setLong(1, ed.getIdEdicio());
stm.setString(2, ed.getNomEdicio());
stm.setLong(3, ed.getIdArea());
stm.setString(4, ed.getArea());
stm.setString(5, ed.getPrograma());
// Conversion from Java Date to SQL Date
java.sql.Date sqlDate = new java.sql.Date(ed.getDataInici().getTime());
logger.info("sqlDate before the insert is: "+ sqlDate); //0011-12-02
stm.setDate(6, sqlDate);
// Data and results commented
logger.info("Id edicio: "+ ed.getIdEdicio()); //6
logger.info("Nom edicio: "+ ed.getNomEdicio()); //test
logger.info("Id area: "+ ed.getIdArea()); //0
logger.info("Nom area: "+ ed.getArea()); //test
logger.info("Programa: "+ ed.getPrograma()); //test
logger.info("Data inici: "+ sqlDate); //2011-06-06
// We are going to execute the insert
int numRows = stm.executeUpdate();
// The program never reaches this point, fails doing the executeUpdate()
logger.info("Rows created: "+ numFiles);
...
The variable types are:
idEdicio = long
nomEdicio = String
idArea = long
area = String
programa = String
dataInici = Date
Can someone help me? Thank you in advance :)
Missing )
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
should be
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
^--- missing parenthesis

Problem with a prepared statement

I have this code:
Date start = new Date(Integer.parseInt(jTextField4.getText()), Integer.parseInt(jTextField16.getText()), Integer.parseInt(jTextField17.getText()));
Date end = new Date(Integer.parseInt(jTextField5.getText()), Integer.parseInt(jTextField18.getText()), Integer.parseInt(jTextField19.getText()));
statement = connection.createStatement();
preparedStatement1 = connection.prepareStatement("insert into sportmangg(customer_code,"
+ "sportman_code, start, finish, salary,amount,box salary,private salary, food salary, "
+ "other salary, bime salary, number) "
+ "values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?");
preparedStatement1.setString(1,jTextField15.getText());
preparedStatement1.setString(2, jTextField1.getText());
preparedStatement1.setDate(3, start);
preparedStatement1.setDate(4, end);
preparedStatement1.setInt(5, Integer.parseInt(jTextField6.getText()) );
preparedStatement1.setInt(6,Integer.parseInt(jTextField14.getText()) );
preparedStatement1.setInt(7, Integer.parseInt(jTextField7.getText()));
preparedStatement1.setInt(8, Integer.parseInt(jTextField8.getText()));
preparedStatement1.setInt(9, Integer.parseInt(jTextField9.getText()));
preparedStatement1.setInt(10, Integer.parseInt(jTextField11.getText()));
preparedStatement1.setInt(11, Integer.parseInt(jTextField10.getText()));
preparedStatement1.setInt(12, Integer.parseInt(jTextField20.getText()));
preparedStatement1.executeUpdate();
but it has this error:
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 'salary,private salary, food salary, other salary, bime salary, number) values ('' at line 1
What is the problem?
You really shouldn't have spaces in the field name. Try surrounding it with ``
Column names with spaces in them are a very bad idea.
If you must have them, surround them with backticks:
`private salary`
You missed ) in the last line of your SQL query so it should be:
+ " values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ? )";
Maybe you can try this:
https://github.com/stuparmihailo/util4j/releases/tag/v1.0
It's some simple project and has nice way for creating statements:
String query = "INSERT INTO table VALUES (?,?,?,?,?,?,?)";
PreparedStatement stmt = con.prepareStatement(query);
StatementUtil.fill(stmt, 45, "text", 2, null, new Date(), false, 3.5);
You should replace private salary with private_salary and keep working with acceptable column name conventions.
column or table names should not have spaces. Join them by underscore. and make them upper case... these are not rules but accepted ways of working with DB objects. If names cannot be changed in the DB and you are stuck with something like some salary, then some salary should help.
mehdi;
I think what you have to do is all of this:
change names of
space-named columns (private salary,
food salary, other salary, bime
salary) either by replacing spaces by underscores
(recommended by naming conventions) or by
surrounding names with grave accent char:
`box salary`, `private salary`, `food salary`, `other salary`, `bime
salary`
Fix this line adding final parentheses
+ "values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?");
it must say:
+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
Finally I'd recommend to take out prepareStatement argument to a String or StringBuffer variable, say "sqlString" or something, so you can manipulate it more transparently. Something like this:
String sqlString = "";
sqlString += " insert into sportmangg";
sqlString += " (customer_code, sportman_code, start, finish,";
sqlString += " salary, amount, box_salary, private_salary,";
sqlString += " food_salary, other_salary, bime_salary, number)";
sqlString += " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
preparedStatement1 = connection.prepareStatement(sqlString);
(or if you use StringBuffer use append method)

Categories

Resources