如何使用prepareStatement来更新数据,字段和值都需要设置

时间:2012-05-28 03:30:27

标签: java oracle prepared-statement sqlexception

我使用prepareStatement()更新数据,因为需要更新几个列,我写了一个这样的程序:

public boolean editSocre(String field, String newValue) 
{
... 

   updateSql = "update score set ? = ? where emp_id = ?";
   pstmt3 = conn.prepareStatement(updateSql);
   pstmt3.setString(1, field);
   pstmt3.setString(2, newValue);
   pstmt3.setString(3, userid);                 
   int row = pstmt3.executeUpdate();
   if (row <= 0) 
   {
      return result;
   }

...

}
  

java.sql.SQLException:ORA-01747:user.table.column无效,   table.column或列规范

如何修改,谢谢!!

2 个答案:

答案 0 :(得分:3)

public boolean editSocre(String field, String newValue) {

... 

updateSql = "update score set "+field+" = ? where emp_id = ?";

pstmt3 = conn.prepareStatement(updateSql);

pstmt3.setString(1, newValue);

pstmt3.setString(2, userid);          

int row = pstmt3.executeUpdate();

if (row <= 0) {

  return result;

}

...

答案 1 :(得分:0)

正如其他答案/评论已经说过:PreparedStatement无法做到这一点。如果要更新的行确实需要是动态的,则可以使用可更新的结果集:

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM score WHERE emp_id = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
stmt.setString(1, userId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) { // or maybe while rs.next()
    rs.updateString(field, newValue);
    rs.updateRow();
}