1. 程式人生 > >JavaWeb開發sql注入詳細例項講解

JavaWeb開發sql注入詳細例項講解

一、在資料庫中插入一條使用者記錄

二、用mysql-connector-java-5.1.15-bin.jar連線資料庫。

建立返回資料庫conn連線的類Db

package com.mysql.zhang;
import java.sql.Connection;
import java.sql.DriverManager;
public class Db {	
private Db() {	
};
private static Connection conn=null;
public static Connection getConn() {
	try {
		String password="root";
		String user="root";
		String url="jdbc:mysql://localhost:3306/test";	
		Class.forName("com.mysql.jdbc.Driver");
		conn=DriverManager.getConnection(url, user, password);
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (Exception e) {	
		e.printStackTrace();
	}
	return conn;	
   }
}
測試類

package com.mysql.zhang;

import java.sql.Connection;
import java.sql.PreparedStatement;
public class Test {
public static void main(String[] args) throws Exception {
    Connection conn=Db.getConn();    
    String sql = "select *from user where name= 'shuibianxie' and password='or1=1'";  
    //name值可以隨便寫
    PreparedStatement pt=conn.prepareStatement(sql);
    System.out.println( "返回查詢結果bool值:"+pt.execute());
    conn.close();
    }
}

三、String sql = "select *from user where name= 'shuibianxie' and password='or1=1'";  

由於資料庫缺陷導致這條語句是恆等的,所以返回true。

試想想一下,如果一個人在使用者登入頁面表單中使用者名稱隨便輸入

密碼輸入or1=1  並且你在伺服器中拼接sql語句,依靠返回的boolean值( pt.execute() )判斷使用者是否登入成功。

那麼就會導致不用資料庫中存在的使用者名稱+密碼就能夠登入成功。