天天看點

JDBC sql注入風險及preparedStatement的使用

問題

sql注入: 通過把SQL指令插入到Web表單送出或輸入域名或頁面請求的查詢字元串,最終達到欺騙伺服器執行惡意的SQL指令

解決辦法

       為了解決這個問題,我們使用preparedStatement來執行sql指令,它的使用跟之前的Statement不太一樣,它不能使用字元串拼接,未知的參數用“?”(占位符)代替,後面可以進行指派,并且它在執行executeQuery和executeUpdate方法時不用傳遞參數。

步驟:

步驟:

        建立集合或者實體類對象(可選-查詢)    

        加載驅動

        擷取連接配接對象

        設定手動資料送出(可選--增删改)

        建立sql指令

        擷取sql指令對象

        給占位符指派

        執行sql語句

        周遊執行結果(可選--查詢)

        送出資料(可選--增删改)

        復原資料(可選-增删改)

        關閉資源

        傳回結果

public User getUSerInfo(String uname, String upwd) throws ClassNotFoundException, SQLException {
        User u=null;
        Connection conn=JdbcUtil.getConnection();
        String sql="select * from t_user where uname=? and upwd=?";
        PreparedStatement ps= JdbcUtil.getPreparedStatement(conn,sql);
        ps.setString(1,uname);
        ps.setString(2,upwd);
        ResultSet rs=ps.executeQuery();
        while(rs.next()){
            u=new User();
            u.setUnum(rs.getInt("unum"));
            u.setUname(rs.getString("uname"));
            u.setUpwd(rs.getString("upwd"));
            return u;
        }

        JdbcUtil.closeAll(rs,ps,conn);

        return u;
    }

    //新增--preparedStatement
    public int insUser2() throws ClassNotFoundException, SQLException{

        //建立連接配接對象
        Connection conn=JdbcUtil.getConnection();
        //建立sql指令
        String sql="insert into t_user values(?,?,?)";
        //建立sql指令對象
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql);
        //給占位符指派
        ps.setInt(1, 7);
        ps.setString(2,"趙六");
        ps.setString(3,"666");
        //執行sql指令
        int i=ps.executeUpdate();
        //關閉資源
        JdbcUtil.closeAll(null,ps,conn);
        //傳回結果
        return i;
    }
    //更新
    public int upUser(String uname,int unum) throws ClassNotFoundException, SQLException {

        //建立連接配接
        Connection conn=JdbcUtil.getConnection();
        //建立sql指令
        String sql="update t_user set uname=? where unum=?";
        //建立sql指令對象
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql);
        ps.setString(1,uname);
        ps.setInt(2,unum);
        int i=ps.executeUpdate();
       JdbcUtil.closeAll(null,ps,conn);
        return i;

    }
    //删除
    public  int delUser(int unum) throws ClassNotFoundException, SQLException {

        Connection conn=JdbcUtil.getConnection();
        //建立sql指令
        String sql="delete from t_user where unum=?";
        //建立sql指令對象
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql);
        ps.setInt(1,unum);
        int i=ps.executeUpdate();
        JdbcUtil.closeAll(null,ps,conn);
        return i;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserDaoImpl2 ud=new UserDaoImpl2();
        User u=ud.getUSerInfo("李四","456");
        System.out.println(u);
    }