赞
踩
SQL语句预编译
SQL语句预编译能预防SQL注入提高安全性,是因为SQL语句在程序运行前已经进行了预编译,在程序运行时第一次操作数据库之前,SQL语句已经被数据库分析,编译和优化,对应的执行计划也会缓存下来并允许数据库以参数化的形式进行查询,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令,就起到了SQL注入的作用。
一、加载驱动
Class.forName("com.mysql.jdbc.Driver");//加载驱动
二、建立连接数据库对象
Connection conn=null;
conn = DriverManager.getConnection("jdbc:mysql:///test","root","root");
三、定义SQL语句,参数为?
String sql="select * from student1 where stunum=?";
四、建立预编译执行对象
PreparedStatement psm = null;
psm=conn.prepareStatement(sql);
五、设置sql语句中的参数值
psm.setString(1,stuNum);
六、定义结果集,把执行对象的查询结果放入rs中
ResultSet rs = null;
rs=psm.executeQuery();
七、打印结果
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);
}
八、关闭资源
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(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。