I am trying to run a method in Java that deletes all records between two dates, however, it gives me a Synax error. This is the code:
public void updateIntegraton(String dateInit, String dateEnd)
{
Connection conn = ConnectionManager.getConnection();
String sql_delete = "DELETE FROM my_schema.my_table WHERE DATE(day_date) BETWEEN DATE(?) AND DATE(?)";
String sql_safe_updates = "SET SQL_SAFE_UPDATES = 0";
PreparedStatement ps_delete;
PreparedStatement ps_safe_updates;
try {
ps_safe_updates = conn.prepareStatement(sql_safe_updates);
System.out.println("Setting safe updates off.");
ps_safe_updates.execute();
ps_delete = conn.prepareStatement( sql_delete );
ps_delete.setString(1, dateInit);
ps_delete.setString(2, dateEnd);
System.out.println("Delete Query: " + ps_delete);
System.out.println("Deleting all records between dates " + dateInit +" and "+ dateEnd);
ps_delete.execute(sql_delete);
System.out.println("Deleted records. ");
} catch (SQLException e) {
System.out.println("Something went wrong on Delete");
e.printStackTrace();
}
}
As you can see, I am printing the delete sql statement after I replace the '?' parameters with values. Here is an example of what it prints on the console:
Delete Query: com.mysql.jdbc.PreparedStatement@1686d1f: DELETE FROM my_schema.my_table WHERE DATE(day_date) BETWEEN DATE('2016-04-01') AND DATE('2016-04-08')
I run that exact same query on MySQL Workbench and rows get deleted, however I get this syntax error when I run my java code:
com.mysql.jdbc.exceptions.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 '?) AND DATE(?)' at line 1
I have used this same syntax to run other sql statements and got no errors. The only thing in my head is that the "execute" method used in the ps_delete.execute(sql_delete) part of my code does not work, but I have used "executeUpdate" and "executeQuery" methods that also give me errors.
I am using the mysql-connector-java-5.0.8-bin.jar library to create the connection to my MySQL library.
Any idea of why this is happening and how can I solve it?
Thanks