当我运行程序时,它会显示列超出范围的错误。连接正常
例如
updateRecoredtoStudent(15, "Annies","Bot"," Ionia", "1/1/2013","firstname","Anny")
private static void updateRecordToStudent(int studentid, String firstname, String lastname,String address, String dateofbirth, String cond_col, String cond_val) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String updateTableSQL = "UPDATE student SET 'studentid' = ? 'firstname' = ? 'lastname' = ? 'address' = ? dateofbirth' = ? WHERE ? = ?";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_col);
preparedStatement.setString(7, cond_val);
// execute update SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is updated to STUDENT table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
Student table contains
-studentid(int-PK)
-Firstname(String)
-lastname(String)
-Address(String)
-Dateofbirth(String)
答案 0 :(得分:2)
将您的SQL语法更改为:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
所以你的SQL UPDATE查询将是:
String updateTableSQL = "UPDATE student SET studentid=?, firstname=?, lastname=?, address=?, dateofbirth=? WHERE " + fieldName + " = ?";
答案 1 :(得分:1)
String updateTableSQL = "UPDATE student SET studentid = ?, firstname = ?, lastname = ?, address = ?, dateofbirth = ? WHERE "+cond_col+" = ?";
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_val);
只能设置列值。如果要传递动态列名,则应使用查询对其进行连接。列名之间还缺少,
。
答案 2 :(得分:0)
我认为你错了代码声明。请尝试以下方法。
String updateTableSQL = "UPDATE student SET 'studentid' = ? 'firstname' = ? 'lastname' = ? 'address' = ? dateofbirth' = ? WHERE " + cond_col + "= ?";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_val);