mysql预编译语句拼接查询_SQL语句预编译(查询)

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值