Java - 转义字符串以防止 SQL 注入

问题描述:

我正在尝试在 Java 中放置一些反 sql 注入,并且发现使用replaceAll"字符串函数非常困难.最终我需要一个函数将任何现有的 \ 转换为 \\,任何 "\",任何'\',以及任何 \n\\n 以便当字符串被 MySQL 评估时SQL 注入将被阻止.

I'm trying to put some anti sql injection in place in java and am finding it very difficult to work with the the "replaceAll" string function. Ultimately I need a function that will convert any existing \ to \\, any " to \", any ' to \', and any \n to \\n so that when the string is evaluated by MySQL SQL injections will be blocked.

我已经添加了一些我正在使用的代码,但函数中的所有 \\\\\\\\\\ 都让我看傻了眼.如果有人碰巧有这样的例子,我将不胜感激.

I've jacked up some code I was working with and all the \\\\\\\\\\\ in the function are making my eyes go nuts. If anyone happens to have an example of this I would greatly appreciate it.

PreparedStatements 是可行的方法,因为它们使 SQL 注入成为不可能.下面是一个以用户输入为参数的简单示例:

PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:

public insertUser(String name, String email) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try {
      conn = setupTheDatabaseConnectionSomehow();
      stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
      stmt.setString(1, name);
      stmt.setString(2, email);
      stmt.executeUpdate();
   }
   finally {
      try {
         if (stmt != null) { stmt.close(); }
      }
      catch (Exception e) {
         // log this error
      }
      try {
         if (conn != null) { conn.close(); }
      }
      catch (Exception e) {
         // log this error
      }
   }
}

无论姓名和电子邮件中是什么字符,这些字符都会直接放入数据库中.它们不会以任何方式影响 INSERT 语句.

No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.

不同的数据类型有不同的设置方法——你使用哪一种取决于你的数据库字段是什么.例如,如果数据库中有一个 INTEGER 列,则应使用 setInt 方法.PreparedStatement 文档列出了所有可用的不同方法用于设置和获取数据.

There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a setInt method. The PreparedStatement documentation lists all the different methods available for setting and getting data.