使用JDBC查询字符串中的Sql语法错误?

时间:2015-06-15 10:56:55

标签: java sql-server jdbc

我正在尝试使用java和jdbc通过timestamp搜索sql中的表,但是当我将时间戳插入查询字符串时,我在小时数字处得到一个sytax错误:

 String queryString = "select " + tag +  " from WATER_RUNTIME_VALUES
 where Time_Stamp = 2015-06-150 8:58:00.0000000";

 ResultSet rs = statement.executeQuery(queryString);

这是错误:

  

com.microsoft.sqlserver.jdbc.SQLServerException:附近的语法不正确   '10'。 at   com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement $ StmtExecCmd.doExecute(SQLServerStatement.java:689)     在   com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)     在   com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)     在   com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)     at bandon.scada.core.InitConn.calculateHourlyTotal(InitConn.java:58)     at bandon.scada.core.InitConn.dbConnect(InitConn.java:36)at   bandon.scada.core.InitConn.main(InitConn.java:24)

4 个答案:

答案 0 :(得分:3)

试试这个..

String queryString = "select ' " + tag + " ' from WATER_RUNTIME_VALUES where Time_Stamp = '2015-06-150 8:58:00.0000000'";

答案 1 :(得分:0)

将单引号放在时间值中以转义2015-06-150 8:58:00.0000000

中的空格
String queryString = "select " + tag + " from WATER_RUNTIME_VALUES where Time_Stamp = '2015-06-150 8:58:00.0000000'";

或者更好地使用PreparedStatement

答案 2 :(得分:0)

在日期参数中使用引号,

String queryString = "select " + tag + " from WATER_RUNTIME_VALUES where Time_Stamp = '2015-06-150 8:58:00.0000000'"

答案 3 :(得分:-1)

日期必须在引号内