sql中Statement与PreparedStatement的区别

32 篇文章 0 订阅
9 篇文章 0 订阅

package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* sql中Statement与PreparedStatement的区别
* 1.Statement用于执行静态sql语句,在执行时,必须指定一个事先准备好的sql语句,也就是说sql语句是静态的。
2.PrepareStatement是预编译的sql语句对象,sql语句被预编译并保存在对象中。
被封装的sql语句代表某一类操作,语句中可以包含动态参数“?”,在执行时可以为“?”动态设置参数值。

3.使用PrepareStatement对象执行sqll时,sql被数据库进行解析和编译,然后被放到命令缓冲区,每当执行同一个PrepareStatement对象时,它就会被解析一次,但不会被再次编译。
在缓冲区可以发现预编译的命令,并且可以重用。所以PrepareStatement可以减少编译次数提高数据库性能。
4.Statement可以被sql注入,而PrepareStatement不能被sql注入
* @author yangjianzhou
*
*/
public class TestJDBC {

public static void main(String[] args) {

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String str = "yangjianzhou";
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncode=utf-8","root","admin");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM students where name ='"+str+"'");
while(rs.next()){
System.out.println(rs.getString("name"));
System.out.println(rs.getString("sex"));
}

PreparedStatement ps = conn.prepareStatement("SELECT * FROM students where name = ? ");
ps.setString(1, "yangjianzhou");
rs = ps.executeQuery();
System.out.println(rs.next());

}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try{
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(stmt != null){
try{
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}




运行结果:

yangjianzhou
male
true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值