准备之一:你已经成功的获取了连接
准备之二:手头一定要有JDK-API
连接使用篇之statemment 与preparedstatement
大多数人都或多或少的听过这两个对象的传言,也应该有印象都是在告诫大家用preparedstatement更好,例如预编译效率快,安全性高,代码更具可读性云云。我们先来看这两个对象的用法(方便起见,我们先假设执行的都是无返回的sql语句,增 删 改)
Statement的使用
/** * Function : a demo for using Statement * * Product describe: * * @throws SQLException * on Aug 23, 2009 BY Simrina */ public void sqlExcuteDemo() throws SQLException{ //连接数据库 this.connectDB(); //当然你也可以换成insert into或者update .. String sql = "delete from user where uid = 1"; //获取Statement对象用于执行Sql语句 Statement stm = this.conn.createStatement(); //执行就这么一句话,简单搞定 stm.execute(sql); //好习惯,有开始,有关闭——当然关闭的时机,你可以选一个你认为更适合的 stm.close(); this.conn.close(); }
2、PreparedStatement的使用
/** * Function : a demo for using Statement * * Product describe: * * @throws SQLException * on Aug 23, 2009 BY Simrina */ public void sqlExcuteDemo(int uid) throws SQLException{ //连接数据库 this.connectDB(); //当然你也可以换成insert into或者update .. String sql = "delete from user where uid = ?"; //获取PreparedStatement对象 PreparedStatement pstm = this.conn.prepareStatement(sql); //设置参数 注意设置参数的方法 pstm.setInt(0, uid); //关闭 pstm.close(); this.conn.close(); }
比较上面两个例子,首先需要注意:Statement和PreparedStatement的获取的方法是不一样的
最后特别关注PreparedStatement设置参数的方法。一般需要对应参数的类型,例如String 类型,则使用setString(parameterIndex,value),同理可证肯定还有setDouble setDate之类的。方法的第一个参数是参数的位置,换句话说,是你sql的问号的位子,从1开始,第一个参数则是参数的value。
所以注意,你可以给语句设置多个参数,当然要类型相对应。
现在我们来谈谈两者的区别,我们一开始说的为什么要推荐PreparedStatement
需要了解prepared的预编译,是需要数据库支持的,不过幸好大部分主流数据库都支持,除了mySQL。所谓的预编译,其实就是相同的Sql语句预先编译并保存起来,之后用到相同的,数据库直接调用已经编译好的语句,节约效率。因此,在相同的一次操作,两者并没有大的性能差异,反而prepared的开销更大一点。
针对有缓存预编译语句的DB而言,预编译的好处在于,如果同一时间有多个用户进行相同语句的操作,或者是打算进行大批量数据处理,或者有一些非常常用的SQL语句,预编译才能明显体现出效率来
最后说一个安全性,举个例子,如果想要查询用户名为Simrina’D的数据,如果你用“select * from user where username = ‘Simrina’D’”,肯定会出错,单引号会提前匹配掉,如果用setString,则可以完整匹配我们整个字符串——姑且当作抛砖引玉
最后,我们来做一个有返回值的查询例子,作为JDBC使用的补完Demo.这个时候不要忘了随时查看,我们准备的API。
/** * Function : 查询数据 * * Product describe: demo 的数据表 uid username * 1 simrina'D * 2 simrina * @return * @throws SQLException * on Aug 24, 2009 BY Simrina */ public List excuteDemo() throws SQLException{ //连接数据库 this.connectDB(); //当然你也可以换成insert into或者update .. String sql = "select * from user"; List lst = new ArrayList(); //获取Statement对象用于执行Sql语句 Statement stm = this.conn.createStatement(); //查询,返回ResultSet——关于ResultSet,自行查询API ResultSet rs = stm.executeQuery(sql); //取数据的简单demo while(rs.next()){ String username = rs.getString("username"); lst.add(username); } //好习惯,有开始,有关闭——当然关闭的时机,你可以选一个你认为更适合的 stm.close(); this.conn.close(); return lst; }
http://code.oseschool.com/index.php/feed