gpt4 book ai didi

java - SQL异常 : executeQuery method can not be used for update

转载 作者:IT老高 更新时间:2023-10-29 00:15:09 27 4
gpt4 key购买 nike

我正在尝试使用 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 的限制或其他我不知道的内容?

提前致谢!

最佳答案

因为您要插入一条记录,所以您应该使用 executeUpdate() 而不是 executeQuery()

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


boolean 执行()

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

结果集执行查询()

Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

int executeUpdate()

Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.


还有一件事,您的查询很弱,因为它容易受到 SQL 注入(inject) 的攻击。请使用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();

关于java - SQL异常 : executeQuery method can not be used for update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006868/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com