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.
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!