防止sql注入漏洞PreparedStatement使用

防止sql注入漏洞PreparedStatement使用

使用传统方法面临sql注入漏洞的风险
PreparedStatement可以防止

1.保存数据


public class JDBCDemo5 {

    @Test
    public void demo1(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            //获得链接
            conn = Utils.getConnection();
            //编写sql
            String sql = "insert into user values (null,?,?,?)";
            //预编译sql
            pstmt = conn.prepareStatement(sql);
            //设置参数
            pstmt.setString(1,"qqq");
            pstmt.setString(2,"123");
            pstmt.setString(3,"家园");
            //执行
            int num = pstmt.executeUpdate();
            if(num>0){
                System.out.println("save success!");
            }
            

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Utils.release(pstmt,conn);
        }
    }
}

2.修改数据

String sql = "update user set username = ?, password = ?, name = ? where uid = ?";
            //预编译sql
            pstmt = conn.prepareStatement(sql);
            //设置参数
            pstmt.setString(1,"www");
            pstmt.setString(2,"123456");
            pstmt.setString(3,"家园");
            pstmt.setInt(4,6);

            //执行
            int num = pstmt.executeUpdate();
            if(num>0){
                System.out.println("save success!");
            }

3.删除数据额

 //获得链接
            conn = Utils.getConnection();
            //编写sql
            String sql = "delete from user where uid = ?";
            //预编译sql
            pstmt = conn.prepareStatement(sql);
            //设置参数
            pstmt.setInt(1,6);

            //执行
            int num = pstmt.executeUpdate();
            if(num>0){
                System.out.println("save success!");
            }

4.查询数据

			//获得链接
            conn = Utils.getConnection();
            //编写sql
            String sql = "select * from user where uid = ?";
            //预编译sql
            pstmt = conn.prepareStatement(sql);
            //设置参数
            pstmt.setInt(1,2);

            //执行
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()){
                int uid = rs.getInt("uid");
                System.out.println(uid);
            }

你可能感兴趣的:(学习笔记,java)