执行更新查询时出现问题,索引1超出范围。
public void updateAnswer(String Answer, String correct, String Id_Question, int id) throws SQLException, Exception {
try {
//UPDATE Answer SET Answer = ':: A. 10 ::B.15 ::C.20 ::D.5' ,Correct_Answer= 'B' WHERE Id = 151;
conn = DataConnection.getConnectionToSQLSever();
sqlStr = "UPDATE Answer SET Answer = '?', Correct_Answer = '?' WHERE Id =?;";
pst = conn.prepareStatement(sqlStr);
pst.setString(1, Answer);
pst.setString(2, correct);
pst.setInt(3, id);
System.out.println(pst.toString());
pst.executeUpdate();
findAnswerId(Id_Question).setAnswer(Answer);
findAnswerId(Id_Question).setCorrect(correct);
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw e;
}
}
答案 0 :(得分:1)
您的前两个问号被视为文字,实际上,您只有一个参数,这就是为什么接收索引超出范围的原因。 删除单引号,?仅凭一个字符串参数就足够了
答案 1 :(得分:0)
尝试此代码。
conn = DataConnection.getConnectionToSQLSever();
sqlStr = "UPDATE Answer SET Answer = ?, Correct_Answer = ? WHERE Id = '" + id + "'";
pst = conn.prepareStatement(sqlStr);
pst.setString(1, Answer);
pst.setString(2, correct);
pst.setInt(3, id);
pst.executeUpdate();