JDBC的SQL注入漏洞分析和解決

1.1.1 SQL注入漏洞分析sql

JDBC的SQL注入漏洞分析和解決
1.1.2 SQL注入漏洞解決ide

須要採用PreparedStatement對象解決SQL注入漏洞。這個對象將SQL預先進行編譯,使用?做爲佔位符。?所表明內容是SQL所固定。再次傳入變量(包含SQL的關鍵字)。這個時候也不會識別這些關鍵字。code

public class UserDao {

         

        public boolean login(String username,String password){

                Connection conn = null;

                PreparedStatement pstmt = null;

                ResultSet rs = null;

                // 定義一個變量:

                boolean flag = false;

                try{

                        // 得到鏈接:

                        conn = JDBCUtils.getConnection();

                        // 編寫SQL語句:

                        String sql = "select * from user where username = ? and password = ?";

                        // 預編譯SQL

                        pstmt = conn.prepareStatement(sql);

                        // 設置參數:

                        pstmt.setString(1, username);

                        pstmt.setString(2, password);

                        // 執行SQL語句:

                        rs = pstmt.executeQuery();

                        if(rs.next()){

                                // 說明根據用戶名和密碼能夠查詢到這條記錄

                                flag = true;

                        }

                }catch(Exception e){

                        e.printStackTrace();

                }finally{

                        JDBCUtils.release(rs, pstmt, conn);

                }

                return flag;

        }
相關文章
相關標籤/搜索