承接上文JDBC-SQL注入簡介. 在大概瞭解了什麼是SQL注入以後,接下來使用test_02
數據庫表模擬用戶登陸操做.sql
提示用戶輸入用戶名和密碼,使用Statement字符串拼接的方式實現用戶登陸數據庫
JDBC-編寫工具類
JDBCUtils
工具類獲取鏈接JDBCUtils
工具類獲取語句執行平臺(即Statement對象)JDBCUtils
工具類關閉對象public class LoginTest01 { public static void main(String[] args) throws SQLException { // 1.獲取鏈接 Connection conn = JDBCUtils.getConnection(); // 2.獲取執行平臺,即Statement對象 Statement sqlExecute = JDBCUtils.createStatement(conn); // 3.提示用戶輸入用戶名和密碼 Scanner sc = new Scanner(System.in); System.out.println("請輸入用戶名: "); String user = sc.nextLine(); System.out.println("請輸入密碼: "); String pass = sc.nextLine(); // 4.執行字符串拼接後的sql語句 String sql = "select * from test_02 where name = '" + user + "' and password = '" + pass + "';"; System.out.println(sql);//查看執行的sql語句 ResultSet resultSet = sqlExecute.executeQuery(sql); // 5.判斷是否登陸成功 if(resultSet.next()){ System.out.println("登陸成功,歡迎:" + user); }else{ System.out.println("登陸失敗!"); } // 5.關閉對象 JDBCUtils.close(conn,sqlExecute,resultSet); } }
如上, 咱們使用一種比較"巧妙"的方式就騙過了登陸驗證
出現這種問題的緣由是使用了字符串拼接. 因此理論上若是咱們不使用字符串拼接,應該就能夠防止SQL注入. 即prepareStatement
segmentfault