最近在项目中,在执行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注入,使得系统安全性能方面有了一定的保证。