我编写了一个简单的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
国家/地区的值为India
来自表单。我该如何解决?
答案 0 :(得分:3)
你的单引号是错误的。
但是从不使用从表单中获取的值插入到数据库中,您可能会遭受SQL注入
http://www.w3schools.com/Sql/sql_injection.asp
使用准备好的语句,其中参数被正确地解析为特定类型
一个例子:
String query = "insert into dept(deptnum, deptname, deptloc) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1); // set input parameter 1
pstmt.setString(2, "deptname"); // set input parameter 2
pstmt.setString(3, "deptLocation"); // set input parameter 3
pstmt.executeUpdate(); // execute insert statement
答案 1 :(得分:1)
您在查询中忘记了'
个字符:
("+fname+"','"+mail+"','"+country+"','"+pword+")
^ here and here ^
将其更改为('"+fname+"','"+mail+"','"+country+"','"+pword+"')
或者更好地使用PreparedStatement
来避免这种错误和SQL注入问题。
String sql = "insert into users (username, email, country, password) values (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// Insert values safe and indirectly to avoid mistakes and SQL injection
preparedStatement.setString(1, fname);
preparedStatement.setString(2, mail);
preparedStatement.setString(3, country);
preparedStatement.setString(4, pword);
// Perform the update
int count = preparedStatement.executeUpdate();