列索引无效,使用PreparedStatement进行更新

时间:2012-02-21 20:39:59

标签: java jdbc oracle11g

我正在使用PreparedStatement

更新表格

以下代码完美无缺

pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname = 'java10'");
int i = pst.executeUpdate();

但是当我尝试这样时它会抛出异常

 pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
 pst.setString(2, "java10"); // yeah second column is jfname

 int i = pst.executeUpdate();

stacktrace:

java.sql.SQLException: Invalid column index
    at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5330)
    at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5318)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:282)
    at com.indus.database.EmployeeDTO.updateData(EmployeeDTO.java:114)

2 个答案:

答案 0 :(得分:9)

以下

2指的是查询字符串中问号的位置,而不是数据库表中列的位置,而不是查询中使用的列名的顺序:

 pst.setString(2, "java10"); // yeah second column is jfname

改用1。

pst.setString(1, "java10"); // first question mark is jfname

答案 1 :(得分:1)

请完成setString()方法规范:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html#setString%28int,%20java.lang.String%29

正确的方法是:

pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(1, "java10"); 

int i = pst.executeUpdate();