Home  >  Article  >  Java  >  How to prevent sql injection in java

How to prevent sql injection in java

青灯夜游
青灯夜游Original
2019-05-06 17:31:144757browse

SQL injection is one of the more common network attack methods. It does not exploit bugs in the operating system to achieve attacks, but targets programmers' negligence during programming. Unscrupulous users take advantage of SQL loopholes and use SQL statements to log in without an account or even tamper with the database. The following article will introduce to you several methods of preventing SQL injection in Java. I hope it will be helpful to you.

How to prevent sql injection in java

#The simplest way to prevent SQL injection in java is to eliminate SQL splicing. SQL injection attacks succeed because new logic is added to the original SQL statement. If PreparedStatement is used instead of Statement to execute the SQL statement, and then only parameters are entered, the SQL injection attack method will be ineffective.

Let’s take a look at how to prevent SQL injection in Java:

1. Use a precompiled statement set, which has built-in ability to handle SQL injection. Just use Its setString method can pass values:

String sql= "select * from users where username=? and password=?;
PreparedStatement preState = conn.prepareStatement(sql);
preState.setString(1, userName);
preState.setString(2, password);
ResultSet rs = preState.executeQuery();

2. Use regular expressions to replace statements containing single quotes ('), semicolons (;) and comment symbols (--) to prevent SQL injection. Example:

public static String SQL(String str)
{
return str.replaceAll(".*([';]+|(--)+).*", " ");
}
userName=SQL(userName);
password=SQL(password);
String sql="select * from users where username='"+userName+"' and password='"+password+"' "
Statement sta = conn.createStatement();
ResultSet rs = sta.executeQuery(sql);

The above is the detailed content of How to prevent sql injection in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does textfield mean?Next article:What does textfield mean?