当前位置: 动力学知识库 > 问答 > 编程问答 >

java - mySQL insert issue from web jsp form containing forward slash character

问题描述:

I have a jsp form where the user can include the following string for example:

This is a test with /

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

description = request.getParameter("description ");

String mysqlQuery= "insert into data values (default,'" + description + "');";

int Res = St.executeUpdate(mysqlQuery);

...

}

Here is the problem. When I go and check mySQL table data, I see that the description column is missing the / :

This is a test with

To workaround that, I tried to use the String.replaceAll method, but this method does not like the '/' or '\' either and the compiler will error. Is there a better way to address this?

网友答案:

Well, Can yo try this once?

preparedStatement = connection.prepareStatement("INSERT INTO data (default, description, .., ....) VALUES (?, ?, ?, ?)");
preparedStatement.setInt(1,0);
preparedStatement.setString(2, data.getDescription());
preparedStatement.setTimestamp(3, ...);
.....

preparedStatement.executeUpdate();

Note: Advantages of a PreparedStatement:

  • Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

  • Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values

  • PreparedStatement is a very good defense (but not foolproof) in preventing SQL injection attacks.

Thanks.

分享给朋友:
您可能感兴趣的文章:
随机阅读: