com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法中有错误; 检查与MySQL服务器版本对应的手册,以便在“firstName”,“lastName”,“email”,“address”,“userName”,“password”附近使用正确的语法。值1(第1行的'nu')
当我运行gui将数据输入表格时,我遇到了上述错误。
我正在使用以下代码
答案 0 :(得分:1)
尝试以下方法在执行前查看查询以找出错误:
public void Create(String first, String last, String email, String address, String username, String password) {
Connection conn = null;
PreparedStatement statement = null;
try {
Class.forName(JDBC_DRIVER).newInstance();
conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
StringBuilder query = new StringBuilder("INSERT INTO person(firstName, lastName, email, address, userName, password) VALUES(")
.append("'").append(first).append("',")
.append("'").append(last).append("',")
.append("'").append(email).append("',")
.append("'").append(address).append("',")
.append("'").append(username).append("',")
.append("'").append(password).append("'")
.append(")");
System.out.println( query.toString());
statement = conn.prepareStatement( query.toString() );
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
}
}
您可以像这样更改submitButton函数:
//action listeners for Login in button and menu item
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String fName = jtfFname.getText();
String lName = jtfLname.getText();
String email = jtfEmail.getText();
String address = jtfAddress1.getText();
String username = jtfUsername.getText();
String password = jtfPassword.getText();
Create(fName , lName, email, address, username, password);
}
});
答案 1 :(得分:1)
不要以这种方式使用预准备语句。您的代码容易受到SQL注入的影响
以这种方式使用预准备语句:
PreparedStatement statement = conn.prepareStatement(
"INSERT INTO person (firstName, lastName, email, address, userName, password) "
+ "VALUES (? , ?, ?, ?, ?, ?)";
statement.setString( 1, first);
statement.setString( 2, last );
statement.setString( 3, email );
statement.setString( 4, address );
statement.setString( 5, username );
statement.setString( 6, password );
statement.executeUpdate();
这也可以防止像撇号一样的愚蠢错误。how to use PreparedStatement
:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
答案 2 :(得分:0)
你在陈述的最后一篇遗漏了'
。您的陈述应该如下:
PreparedStatement statement =
conn.prepareStatement("INSERT INTO person ('firstName', 'lastName', 'email',
'address', 'userName', 'password') "
+ "VALUES ('" + first + "', '" + last + "', '" + email + "',
'" + address + "', '" + username + "', '" + password + "')");