dan*_*sim 13 java mysql sql servlets
我试图使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
但我一直得到以下例外:
java.sql.SQLException: executeQuery method can not be used for update.
Run Code Online (Sandbox Code Playgroud)
这究竟是什么意思?
SQL命令是正确的,因为我可以在NetBeans SQL命令窗口中手动执行此操作.
servlet或我不知道的东西有限制吗?
提前致谢!
Joh*_*Woo 23
既然你插入一条记录,你应该使用executeUpdate()没有executeQuery().
以下是一些通常被滥用的方法:
boolean execute()
在此PreparedStatement对象中执行SQL语句,该对象可以是任何类型的SQL语句.
ResultSet executeQuery()
在此PreparedStatement对象中执行SQL查询,并返回查询生成的ResultSet对象.
int executeUpdate()
执行此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();
Run Code Online (Sandbox Code Playgroud)