Statement和PreparedStatement的区别
2015-09-12 03:16
477 查看
最近在项目中,在执行sql进行数据库操作时,经常会遇到 Statement对象和PreparedStatement对象,那他们有什么区别,又在何时用呢?
二者关系:PreparedStatement接口继承了Statement接口。
相同点:都是数据库执行的方法,用来发送要执行的sql语句。
我们通过具体例子还比较一下这两个的区别。
Statement的使用:
PreparedStatement的使用:
执行过程:
创建相应对象——>执行语句——>语句完成,关闭对象。
执行语句有三种方法:executeQuery(查询,返回单个结果集)、executeUpdate(增删改) 和 execute(多个结果集)。
Statement 对象用于执行不带参数的简单 SQL 语句,PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句。什么意思呢?"PreparedStatement"从字面来看,"Prepared"意为“准备好的”,PreparedStatement 实例包含已编译的
SQL 语句,它的sql语句可带参数,也可不带。
那么这两种方法,有何优劣呢?
对于只执行一次的SQL语句选择Statement是最好的. 相反, 如果SQL语句被多次执行选用PreparedStatement是比较好的.PreparedStatement的第一次执行消耗是很高的. 它的性能体现在后面的重复执行.另外,参数化查询的方式也在一定程度上防止了sql注入,使得系统安全性能方面有了一定的保证。
二者关系: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注入,使得系统安全性能方面有了一定的保证。
相关文章推荐
- 【转】使用maven 如何生成源代码的jar包
- LeetCode Triangle
- Leet Code 20 Valid Parentheses
- LeetCode Triangle
- Leet Code 19 Remove Nth Node From End of List
- 常见安卓主题显示
- Leet Code Medium 18 4Sum
- 【小熊刷题】3Sum Closest <Leetcode 16, Java>
- Part 98 Anonymous methods in c#
- 八大排序算法
- 教你如何迅速秒杀掉:99%的海量数据处理面试题
- 学长们的求职血泪史(C/C++/JAVA)
- Majority Element II
- 计票统计
- 设计模式交流会总结
- Zabbix 监控 Nginx
- Flash Stage3D 在2D UI 界面上显示3D模型问题完美解决
- POJ 2155 解题报告
- Effective C++ 条款46 需要类型转换时请为模板定义非成员函数
- Codeforces Round #319 (Div. 2)(A,B,C,E)