我在尝试对MySql数据库表中的行(记录)求和求和时遇到错误。我要实现的是更新Total_Score
表中的term1
列。如果任何分数都有变化,那么我必须相应地更新Total_Score
列。以下是给出错误的部分编码。
String qry2 = null;
Prepared statement ps2 = null;
qry2 = " UPDATE term1 SET Total_Score = sum(English + Social_Science + Science + Maths + PE + MAL Arts) WHERE SID = ?";
ps2.=conn.prepareStatement(qry2);
Int res2=ps2.executeUpdate();
该代码中有很多错误:
String qry2 = null;
Prepared statement ps2 = null; // Data type is `PreparedStatement`, not `Prepared statement`
// Don't call `sum()` unless you're summing multiple rows, and you're not.
// What is `MAL Arts`? Column names cannot have spaces, unless you quote
// the name, and you really don't want to be doing that.
qry2 = " UPDATE term1 SET Total_Score = sum(English + Social_Science + Science + Maths + PE + MAL Arts) WHERE SID = ?";
ps2.=conn.prepareStatement(qry2); // no period before =
Int res2=ps2.executeUpdate(); // Data type is `int`, not `Int`
似乎您的代码应该是:
String qry2 = "UPDATE term1" +
" SET Total_Score = English + Social_Science + Science + Maths + PE + MALArts" +
" WHERE SID = ?";
int res2;
try (PreparedStatement ps2 = conn.prepareStatement(qry2)) {
ps2.setInt(1, sid);
res2 = ps2.executeUpdate();
}
// code using `res2` here