I get an syntax error while trying to INSERT some values to Mysql from Java.
My code looks like this:
date = new SimpleDateFormat("yyyy-MM-dd").parse(nextLine[0]);
java.sql.Timestamp sqlDate = new java.sql.Timestamp(date.getTime());
st.executeUpdate("INSERT INTO " + tick + "(day, open, high, low, close, volume) VALUES (" + sqlDate + ", " + nextLine[1] + ", " + nextLine[2] + ", " + nextLine[3] + ", " + nextLine[4] + ", " + nextLine[5] + ")");
My 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 ’00:00:00.0,
128.40, 128.50, 127.30, 128.20, 1415200)’ at line 1
Would be glad for any help 🙂
While it would be possible to just fix the immediate syntax error, I would strongly recommend against it. You shouldn’t be including the values directly in your SQL at all.
Instead, use a parameterized query via
PreparedStatement, and set your values into the parameters instead. In this case, you’d usePreparedStatement.setTimestampto set the value – after changing the query to be parameterized in the first place, of course.Benefits of parameterized SQL: