Statement和PreparedStatement的区别

       最近在项目中,在执行sql进行数据库操作时,经常会遇到 Statement对象和PreparedStatement对象,那他们有什么区别,又在何时用呢?

       二者关系:PreparedStatement接口继承了Statement接口。

       相同点:都是数据库执行的方法,用来发送要执行的sql语句。


      我们通过具体例子还比较一下这两个的区别。

Statement的使用:

String sql="delete from t_user where user_id in("+sbStr.substring(0,sbStr.length()-1)+")";
	
		Connection conn=null;
		Statement stmt=null;
		//建立连接
	        conn=DbUtil.getConnection();
		//发送执行的sql
		stmt=conn.createStatement();
		stmt.executeUpdate(sql);


PreparedStatement的使用:

String sql = "insert into t_user (user_id, user_name, password, contact_tel, email, create_date) " +
		" values (?, ?, ?, ?, ?, ?)";
		Connection conn=null;
		PreparedStatement pstmt=null;
		
		//建立连接
		conn=DbUtil.getConnection();

		pstmt=conn.prepareStatement(sql);
		//设置参数
		pstmt.setString(1,user.getUserId());
		pstmt.setString(2,user.getUserName());
		pstmt.setString(3,user.getPassword());
		pstmt.setString(4,user.getContactTel());
		pstmt.setString(5,user.getEmail());
		pstmt.setTimestamp(6,new Timestamp(System.currentTimeMillis()));
		pstmt.executeUpdate();


 执行过程:

          创建相应对象——>执行语句——>语句完成,关闭对象。

         执行语句有三种方法:executeQuery(查询,返回单个结果集)、executeUpdate(增删改) 和 execute(多个结果集)。


       Statement 对象用于执行不带参数的简单 SQL 语句,PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句。什么意思呢?"PreparedStatement"从字面来看,"Prepared"意为“准备好的”,PreparedStatement 实例包含已编译的 SQL 语句,它的sql语句可带参数,也可不带。


       那么这两种方法,有何优劣呢?

       对于只执行一次的SQL语句选择Statement是最好的. 相反, 如果SQL语句被多次执行选用PreparedStatement是比较好的.PreparedStatement的第一次执行消耗是很高的. 它的性能体现在后面的重复执行.另外,参数化查询的方式也在一定程度上防止了sql注入,使得系统安全性能方面有了一定的保证。


转载于:https://www.cnblogs.com/saixing/p/6730267.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值