public void updateDeduction(String empId, String dedId, String dedname,String dedamount,String date) throws SQLException{
//update the contributions
stmt = conn.createStatement();
String updateString ="INSERT INTO deductions (empId,dedId,dedName,dedAmount,dedDate) VALUES (";
updateString +="'"+empId+"', ";
updateString +="CURDATE(), " ;
updateString +="'"+dedId+"'";
updateString +="'"+dedname+"', ";
updateString +="'"+dedamount+"')";
stmt.executeUpdate(updateString);
return;
每当我点击扣除标签时,我都会收到错误,请告诉我该怎么做?
答案 0 :(得分:4)
最好使用PreparedStatement
代替Statement
。它可以帮助您防止sql injection
攻击。尝试构建PreparedStatement
之类的 -
String updateString ="INSERT INTO deductions (empId, dedId, dedName, dedAmount, dedDate) VALUES (?,?,?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(updateString);
preparedStatement.setInt(1, empId);
preparedStatement.setInt(2, dedId);
preparedStatement.setString(3, dedName);
preparedStatement.setDouble(4, dedAmount);
preparedStatement.setDate(5, dedDate);
preparedStatement .executeUpdate();
答案 1 :(得分:1)
执行此操作的正确方法是使用PreparedStatement。我在下面重写了OP代码,以说明如何完成:
public void updateDeduction(String empId, String dedId, String dedname,String dedamount,String date) throws SQLException{
//update the contributions
PreparedStatement updateString = conn.prepareStatement("INSERT INTO deductions (empId,dedId,dedName,dedAmount,dedDate) VALUES (?, ?, ?, ?, ?)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); // you passed in CURDATE() instead of using one of your parameters.
updateString.setString(1, empId);
updateString.setString(2, dedId);
updateString.setString(3, dedName);
updateString.setString(4, dedAmount);
updateString.setString(5, date); // you were missing this line
if (updateString.executeUpdate() == 1) return;
else throw new RuntimeException("Update failed");
}
对我的代码的一些评论应该让我更清楚为什么我使用这种风格。 if行存在以确保插入成功,因为executeUpdate被定义为返回插入上下文中插入的行数。此外,如果必须声明您的语句完全更改行,则它们可以声明为可更新。希望这会有所帮助,如果您需要进一步的帮助/解释,请在这里发表评论。
答案 2 :(得分:0)
updateString +="'"+dedId+"'";
此外,您连接到字符串的值的顺序与INSERT INTO (...)
修复将类似于
updateString +="'"+empId+"', ";
updateString +="'"+dedId+"', "; //Or updateString += dedId+", "; If dedId is an integer value in the database.
updateString +="'"+dedname+"', ";
updateString +="'"+dedamount+"', ";
updateString +="CURDATE())" ;
注意我已重新排序字符串连接以匹配INSERT INTO (...)
字段顺序,除了最后一个字段外,所有字段都有逗号。