java.sql.SQLException Parameter index out of range (0 1 ).

不能 preparedStatement.setString(0, "" + account_no); 導致: java.sql.SQLException: Parameter index out of range (0 < 1 ).
 
 我的代碼如下:
PreparedStatement preparedStatement = connection
    .prepareStatement("select * from  account where account_no = '#{account_no}';");
preparedStatement.setString(1, "" + account_no);
ResultSet resultSet = preparedStatement.executeQuery();
String x = null;
while (resultSet.next()) {
   boolean next = resultSet.next();
   double aDouble = resultSet.getDouble(1);
   double freezed_amount = resultSet.getDouble(2);
   x = aDouble + " -- " + freezed_amount;
   System.out.println(x);
}

 

 
不能這樣 preparedStatement.setString(0, "" + account_no);
 
而是 preparedStatement.setString(1, "" + account_no);
 
因爲
parameterIndex 從1 開始..
 
java.sql.PreparedStatement void setString(int parameterIndex,
               String x)
throws SQLException
Sets the designated parameter to the given Java String value. The driver converts this to an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's limits on VARCHAR values) when it sends it to the database.

Params:
parameterIndex – the first parameter is 1, the second is 2, ...
x – the parameter value
Throws:
SQLException – if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed PreparedStatement

 

ResultSet 的 getXxx方法也是 從1 開始;官方的註釋是:
java.sql.ResultSet public abstract double getDouble(int columnIndex) throws java.sql.SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language. Params: columnIndex – the first column is 1, the second is 2, ... Returns: the column value; if the value is SQL NULL, the value returned is 0 Throws: java.sql.SQLException – if the columnIndex is not valid; if a database access error occurs or this method is called on a closed result set
 
+++++++++++
 
where account_no = #{account_no}
where account_no = '#{account_no}'
where account_no = '?'
上面三種sql 報錯:java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
 
所以只能 where account_no = ?
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章