Java - 转义字符串以防止SQL注入 [英] Java - escape string to prevent SQL injection

查看:156
本文介绍了Java - 转义字符串以防止SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在java中放置一些反sql注入,我发现使用replaceAll字符串函数非常困难。最终我需要一个函数,将任何现有的 \ 转换为 \\ ,任何 \,任何' \\',以及任何 \\\
\\\\
该字符串由MySQL SQL注入进行评估将被阻止。



我已经填补了我正在使用的代码,所有的 \\\\\\\\\该功能中的\\\ 使我的眼睛变得坚强。如果有人有这个例子,我会非常感激。

解决方案

PreparedStatements是要走的路,因为他们SQL注入不可能。这是一个简单的例子,以用户的输入为参数:

  public insertUser(String name,String email){
连接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(异常e){
//记录此错误
}
try {
if(conn!= null){conn。关(); }
}
catch(异常e){
//记录此错误
}
}
}

无论名称和电子邮件中有哪些字符,这些字符都将直接放在数据库中。它们不会以任何方式影响INSERT语句。



不同的数据类型有不同的设置方法 - 您使用的方法取决于您的数据库字段。例如,如果数据库中有一个INTEGER列,则应使用 setInt 方法。 PreparedStatement文档列出了所有可用的不同方法用于设置和获取数据。


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 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
      }
   }
}

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.

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.

这篇关于Java - 转义字符串以防止SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆