I have a query that throws a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
and I can't figure out why. I am using xampp and when I try the same query directly, it works fine. I also have a whole bunch of other methods that use very similar queries that all work.
The problem seems to be with updating the date, I noticed in the error message that java puts ' ' around the date, which makes it a string and is probably the reason for the error. However I'm not sure how to fix this to insert the date as a date.
Here's the code:
public void update(int userId, String date, String column, String value){
try {
// convert date from String to Date
DateTime dt = DateTime.parse(date);
java.sql.Date sqlDate = new java.sql.Date(dt.getMillis());
// create prepared statement
conn = DriverManager.getConnection("jdbc:mysql://localhost/db","root", "");
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = CAST(? AS DATETIME);";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, column);
preparedStmt.setString(2, value);
preparedStmt.setInt(3, userId);
preparedStmt.setDate(4, sqlDate);
preparedStmt.executeUpdate();
conn.close();
} catch (Exception e) {
System.err.println("MySQL exception: " + e);
}
}
And the error message:
MySQL exception: 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 ''comment' = '123' WHERE userId = 1 AND date = CAST('2018-01-06' AS DATETIME)' at line 1
I also tried the query without casting as datetime:
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = ?;";
But I get the same error.
I then tried to use java.util.Date
instead of Joda DateTime
, but it doesn't help. Any ideas?
Thanks!