I. Introduction to SQL Injection
SQL Injection changes the logic structure of the original SQL statement, so that the execution result of the SQL statement is different from that of the original developer;
Method: Submit the command to the program as a user input in the form;
Ii. SQL Injection examples
Based on the user logon page
<Form action = ""> User name: <input type = "text" name = "username"> <br/> password: <input type = "password" name = "password"> <br/> </form>
Create a table in advance:
create table user_table(idintPrimary key,usernamevarchar(30),passwordvarchar(30));
insert into user_table values(1,'xiazdong-1','12345');insert into user_table values(2,'xiazdong-2','12345');
The code for querying a database is as follows:
public class Demo01 {public static void main(String[] args) throws Exception {String username = "xiazdong";String password = "12345";String sql = "SELECT id FROM user_table WHERE " + "username='" + username+ "'AND " + "password='" + password + "'";Class.forName("com.mysql.jdbc.Driver");Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","12345");PreparedStatement stat = con.prepareStatement(sql);System.out.println(stat.toString());ResultSet rs = stat.executeQuery();while(rs.next()){System.out.println(rs.getString(1));}}}
But here username = xiazdong, password = 12345,
Therefore, the SQL statement here is:
SELECT id FROM user_table WHERE username='xiazdong' AND password='12345';
If we change the values of username and password:
Username = 'or 1 = 1 --
Password = x
It turns into a terrible situation: all users in the database are listed. Why?
Because the SQL statement is:
SELECT id FROM user_table WHERE username='' OR 1=1 -- ' AND password='12345';
Because -- indicates SQL comments, the subsequent statements are ignored;
Because 1 = 1 is always established, username = ''or 1 = 1 is always established, so the SQL statement is equivalent:
SELECT id FROM user_table;
It's amazing ....
Iii. Solution
In fact, the solution is very simple, that is, use preparedstatement;
Finally, an SQL injection image is introduced: