1
 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;

每当我点击扣除选项卡时,我都会收到错误消息,请告诉我该怎么做?

4

3 回答 3

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();
于 2013-01-05T06:21:52.383 回答
1

正确的方法是使用PreparedStatement。我在下面重写了 OPs 代码来展示它是如何完成的:

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被定义为返回插入上下文中插入的行数。此外,如果您的语句完全更改行,则必须将它们声明为可更新的。希望这会有所帮助,如果您需要进一步的帮助/解释,请在此处发表评论。

于 2013-01-05T06:27:29.877 回答
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 (...)字段顺序,并且所有字段后面都有逗号,除了最后一个。

于 2013-01-05T06:06:20.400 回答