Java Mysql删除日期之间的记录语法错误

时间:2016-04-08 16:31:40

标签: java mysql sql syntax-error sql-delete

我正在尝试在Java中运行一个删除两个日期之间所有记录的方法,但是,它给了我一个Synax错误。这是代码:

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();
    }
}

正如您所看到的,我在替换'?'之后打印了删除sql语句。带有值的参数。以下是它在控制台上打印的示例:

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')

我在MySQL Workbench上运行完全相同的查询并删除行,但是当我运行java代码时出现此语法错误:

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

我使用相同的语法来运行其他sql语句并且没有错误。我唯一想到的是"执行"我的代码的ps_delete.execute(sql_delete)部分中使用的方法不起作用,但我使用了" executeUpdate"和" executeQuery"方法也给我错误。

我正在使用mysql-connector-java-5.0.8-bin.jar库来创建与MySQL库的连接。

知道为什么会这样,我该怎么解决?

由于

2 个答案:

答案 0 :(得分:3)

 ps_delete.execute();

在我看来它应该是:

nvcc beispielklasse.cu -run -ccbin "C:/Program Files (x86)/Microsoft Visual Studio 11.0/VC/bin" -arch=compute_30

答案 1 :(得分:0)

引用StackOverflow上的另一篇文章你应该使用setDate方法。 [JDBC: Inserting Date values into MySQL

您的代码应该是这样的:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    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.**setDate**(1, sdf.parse(dateInit));
        ps_delete.**setDate**(2, sdf.parse(dateEnd));

        ps_delete.execute();

    } 

我不会尝试代码,只是写一下,让你知道它是如何工作的。 让我知道