由于您要插入记录,因此应使用
executeUpdate()not
executeQuery()。
以下是一些通常被滥用的方法:
布尔型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();
- Java PreparedStatement



