1

我在以下代码片段中收到 SQL 语法错误。这里有什么问题?我无法弄清楚。请帮忙。

String selectSQL = "SELECT * FROM cost_info where `date` > ? and `date` < ?  order by `date`";
        PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);

        java.sql.Date sqlFromDate = java.sql.Date.valueOf(from_date);
        java.sql.Date sqlEndDate = java.sql.Date.valueOf(end_date);

        preparedStatement.setDate(1, sqlFromDate );
        preparedStatement.setDate(2, sqlEndDate );
        rs = preparedStatement.executeQuery(selectSQL);

我正在使用 MySQL。错误是:

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 '? and `date` < ?  order by `date`' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2619)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2569)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1521)
at com.source.viralmo.rms.CostDisplay.initialize(CostDisplay.java:77)
at com.source.viralmo.rms.CostDisplay.<init>(CostDisplay.java:34)
at com.source.viralmo.rms.AdminPage.actionPerformed(AdminPage.java:141)
4

4 回答 4

2
SELECT * FROM cost_info order by date where date > ? and date < ?

你放order by错地方了,应该在查询的最后。

SELECT * FROM cost_info where date > ? and date < ?  order by date
于 2012-10-16T06:25:19.873 回答
2

首先,order by应该去追求where

其次,如果您使用的是 MySQL,date则应该引用它,因为它是该DATE类型的保留字。查询应该是:

SELECT * FROM cost_info where `date` > ? and `date` < ?  order by `date`

executeQuery()第三,使用该方法执行准备好的语句。这里使用的executeQuery(String)方法是执行普通语句;例如,它不替换参数,因此按?原样传递给数据库。你需要:

rs = preparedStatement.executeQuery(/* empty */);
于 2012-10-16T06:28:08.357 回答
1

Order by 子句在 where 子句之后

于 2012-10-16T06:25:47.317 回答
1

SELECT * FROM cost_info where date > ? and date < ? order by date在你的情况下是正确的 sql

于 2012-10-16T06:26:14.180 回答