1

我正在尝试根据 DATETIME 从表中选择条目的子集。在命令行中,我输入

SELECT * FROM routes_table WHERE time > '2012-05-28 11:01:01' ORDER BY time

我明白了

mysql> SELECT * FROM routes_table WHERE time > '2012-05-28 11:01:01' ORDER BY time;
+-----------+--------------+------+---------------------+--------------+
| driver    | type         | num  | time                | destination  |
+-----------+--------------+------+---------------------+--------------+
| Ma Lvjing | Bus          | B127 | 2012-06-22 15:00:00 | Colina Hotel |
+-----------+--------------+------+---------------------+--------------+
1 row in set (0.00 sec)

但是,当通过 JDBC 执行完全相同的查询时,我会得到表的所有结果,包括时间早于 '2012-05-28 11:01:01' 的条目。知道为什么会这样吗?

这是 JDBC 代码的一部分,在 JSP 中

String database = "routes";
String routes_table = "routes_table";
String column_time = "time";
<%
    try {
        Class.forName("com.mysql.jdbc.Driver"); //Load the MySQL driver
        con = DriverManager.getConnection("jdbc:mysql://localhost/"
                + database, "root", "admin");
        stmt = con.createStatement();

        String currentDATETIME = new TimeToolbox().getCurrentDATETIME();

        rs = stmt.executeQuery("SELECT * FROM " + routes_table + " WHERE "
                + column_time + " > '" + currentDATETIME + "'"
                + " ORDER BY " + column_time);
%>
4

1 回答 1

1

您应该使用带有参数和日期变量的准备好的语句来传递日期的值,这样您最有可能解决问题并防止 SQL 注入...

String query = "SELECT * FROM " + routes_table + " WHERE "
                + column_time + " > ?"
                + " ORDER BY " + column_time;
PreparedStatement prest = con.prepareStatement(query);
prest.setDate(1,new Date());
于 2012-05-28T06:08:37.287 回答