【发布时间】:2015-12-15 21:39:55
【问题描述】:
我在这里和其他地方看到过这样的例子。
在 IN CLAUSE 中使用 '1' 参数我成功了:
SELECT AVG( ( High_Temperature + Low_Temperature ) / 2.0 )
FROM obs_masterAll
WHERE Observation_Valid_Time = ? AND
Location_ID IN ( ? );
Microsoft JDBC Driver 4.2 for SQL Server 4.2.6420.100
Parameter Count = 2
2010, 36.5
但是,在 IN CLAUSE 中有多个参数,我明白了:
SELECT AVG( ( High_Temperature + Low_Temperature ) / 2.0 )
FROM obs_masterAll
WHERE Observation_Valid_Time = ?
AND Location_ID IN ( ?, ? ); <--- PROBLEM HERE
Microsoft JDBC Driver 4.2 for SQL Server 4.2.6420.100
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ','.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerParameterMetaData.<init>(SQLServerParameterMetaData.java:423)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.getParameterMetaData(SQLServerPreparedStatement.java:1659)
at CreateAMultiStationDailyLoadCtrAvgHistogram.main(CreateAMultiStationDailyLoadCtrAvgHistogram.java:68)
Java Result: 1
这是我的代码:
prepStmt = buildPreparedStatement( conn.getConnectionObject() ); //function below
conn.printDriverInfo();
sqlDate = new java.sql.Date( beginDate.getTimeInMillis() );
ParameterMetaData pmData = prepStmt.getParameterMetaData();
System.out.println( "Parameter Count = " + pmData.getParameterCount() );
prepStmt.setDate( 1, sqlDate );
for( i = 0; i < locID.size(); i++ )
{
prepStmt.setString( ( i + 2 ), locID.get(i) );
}
rslt = prepStmt.executeQuery();
private PreparedStatement buildPreparedStatement(java.sql.Connection con)
throws SQLException
{
int i;
StringBuilder sb = new StringBuilder();
sb.append("SELECT AVG( ( High_Temperature + Low_Temperature ) / 2.0 ) ");
sb.append("FROM obs_masterAll ");
sb.append("WHERE Observation_Valid_Time = ? AND " );
sb.append("Location_ID IN ( " );
for( i = 0; i < ( locID.size() - 1 ); i++ )
{
sb.append( "?" ).append(", ");
}
sb.append( "?" ).append(" );");
System.out.println( sb.toString() );
return( con.prepareStatement( sb.toString() ) );
}
问题是我的代码还是 JDBC 驱动程序?
【问题讨论】:
-
您没有正确地将值分配给占位符。你在 forst for 循环中写了 i
-
“客人” --> 非常感谢您的快速回复!我相信问题出在 SQL 语法上(根据上面堆栈跟踪的第一行)。代码在创建 ParameterMetaData 对象时出错,甚至没有分配参数。