14

我正在尝试使用 java servlet 类将从注册表中获取的用户信息插入 Derby DB。

在用户单击填写了用户信息的提交按钮后,我立即连接到 NetBeans 上的数据库。然后它应该运行这个方法:

public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
    try {
        stmt = conn.createStatement();
        String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
        System.out.println(insertNewUserSQL);
        stmt.executeQuery(insertNewUserSQL);
        stmt.close();
    } catch(SQLException sqlExcept) {
        sqlExcept.printStackTrace();
    }
}

但我不断收到以下异常:

java.sql.SQLException: executeQuery method can not be used for update.

这到底是什么意思?

SQL 命令是正确的,因为我可以在 NetBeans SQL 命令窗口中手动执行它。

servlet 是否有限制或我不知道的东西?

提前致谢!

4

2 回答 2

26

由于您要插入记录,因此您应该使用executeUpdate()not executeQuery()

以下是一些通常被误用的方法:


布尔执行()

执行此 PreparedStatement 对象中的 SQL 语句,该对象可以是任何类型的 SQL 语句。

结果集执行查询()

在此 PreparedStatement 对象中执行 SQL 查询,并返回查询生成的 ResultSet 对象。

诠释执行更新()

执行此 PreparedStatement 对象中的 SQL 语句,该语句必须是 SQL INSERT、UPDATE 或 DELETE 语句;或不返回任何内容的 SQL 语句,例如 DDL 语句。


还有一件事,您的查询很弱,因为它很容易受到SQL Injection. 请使用 进行参数化PreparedStatement

示例代码片段:

String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
于 2013-04-15T02:42:09.617 回答
1

要更新值,您需要使用可更新的 ResultSet,如下所示:

ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();

或者,您可以使用语句的 executeUpdate 方法,如下所示: statement.executeUpdate("update table set id = 2");

于 2013-04-15T02:43:02.937 回答