【发布时间】:2016-11-23 10:00:38
【问题描述】:
我编写了一个简单的 java 代码来接受来自表单的参数并将其存储在一个表中。这是代码:
String fname = request.getParameter("username");
String mail = request.getParameter("email");
String country = request.getParameter("country");
String pword = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/foodforthought", "root",
"********");
Statement statement = connection.createStatement();
try {
int i = statement.executeUpdate("insert into users (username,email,country,password) values ("+fname+"','"+mail+"','"+country+"','"+pword+")");
out.println("Successfully registered");
} catch (Exception e) {
out.println(e);
e.printStackTrace();
}
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'India',')' at line 1
country 的值为India,来自表单。我该如何解决?
【问题讨论】:
-
您在第一个括号之后和
values部分的最后一个括号之前缺少引号。最好使用PreparedStatement来避免这个问题和可能的注入。 -
'"+pword+"你最后少了一个单引号。 -
int i = statement.executeUpdate("insert into users (username,email,country,password) values ('"+fname+"','"+mail+"','"+country+"','"+pword+"')");