当前位置:   article > 正文

SQL语句预编译(查询)_预编译查询

预编译查询

SQL语句预编译

SQL语句预编译能预防SQL注入提高安全性,是因为SQL语句在程序运行前已经进行了预编译,在程序运行时第一次操作数据库之前,SQL语句已经被数据库分析,编译和优化,对应的执行计划也会缓存下来并允许数据库以参数化的形式进行查询,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令,就起到了SQL注入的作用。
  • 1

一、加载驱动

Class.forName("com.mysql.jdbc.Driver");//加载驱动
  • 1

二、建立连接数据库对象

Connection conn=null;
conn = DriverManager.getConnection("jdbc:mysql:///test","root","root");
  • 1
  • 2

三、定义SQL语句,参数为?

 String sql="select * from student1 where stunum=?";
  • 1

四、建立预编译执行对象

PreparedStatement psm = null;
psm=conn.prepareStatement(sql);
  • 1
  • 2

五、设置sql语句中的参数值

psm.setString(1,stuNum);
  • 1

六、定义结果集,把执行对象的查询结果放入rs中

ResultSet rs = null;
rs=psm.executeQuery();
  • 1
  • 2

七、打印结果

while (rs.next()){
                String stunum=rs.getString(1);
                String stuname=rs.getString(2);
                String stuclass=rs.getString(3);
                System.out.println("查询学生信息如下:");
                System.out.println(stunum+" "+stuname+" "+stuclass);
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

八、关闭资源

            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (psm!=null){
                try {
                    psm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/425490
推荐阅读
相关标签
  

闽ICP备14008679号