Home > Java > javaTutorial > body text

How to prevent sql injection in java?

藏色散人
Release: 2020-10-12 17:33:11
Original
12356 people have browsed it

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();
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template