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

How to prevent sql injection in java?

藏色散人
藏色散人Original
2019-04-30 09:37:3612285browse

SQL injection is one of the more common network attack methods. It does not use the BUG of the operating system to achieve the attack, but targets the programmer's negligence during programming. Through SQL statements, it can log in without an account or even tamper with the database.

How to prevent sql injection in java?

Java background method to prevent SQL injection:

1. Use a precompiled statement set, which has built-in ability to handle SQL injection , just use its setString method to pass the value:

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 (--) Fall to prevent SQL injection

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);

Related recommendations: "Java Tutorial"

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