日期:2014-05-20  浏览次数:20693 次

PreparedStatement的问题
java的文档是这样写的

An   object   that   represents   a   precompiled   SQL   statement.

A   SQL   statement   is   precompiled   and   stored   in   a   PreparedStatement   object.   This   object   can   then   be   used   to   efficiently   execute   this   statement   multiple   times.  

那么如果这个PreparedStatement对象回收之后,这个SQL是不是就不再是precompiled的了?从网上找了些资料,说SQL是被Cache在数据库的,但是自己也作了测试,好像有点问题。

测试代码如下:
try{
    Connection   conn   =   JdbcConnectionUtil.getConnection();
long   l   =   System.currentTimeMillis();
long   l1   =   System.currentTimeMillis();
///*
for(int   I   =   0;   I   <   20;   ++I){
PreparedStatement   ps   =   conn.prepareStatement( "select   *   from   tablename   where   ID   =   "   +   (I)   );
        ResultSet   rs   =   ps.executeQuery();
        System.out.println( "--------------- "+(System.currentTimeMillis()-l));
        l   =   System.currentTimeMillis();
}
System.out.println( "------------------------------------- "   +   (System.currentTimeMillis()-l1));
long   l2   =   System.currentTimeMillis();
for(int   I   =   0;   I   <   20;   ++I){
PreparedStatement   ps   =   conn.prepareStatement( "select   *   tablename   where   ID   =   ? ");
ps.setInt(1,I);
        ResultSet   rs   =   ps.executeQuery();
        System.out.println( "--------------- "+(System.currentTimeMillis()-l));
        l   =   System.currentTimeMillis();
}
System.out.println( "------------------------------------- "   +   (System.currentTimeMillis()-l2));


long   l3   =   System.currentTimeMillis();
PreparedStatement   ps   =   conn.prepareStatement( "select   *   tablename   where   ID   =   ? ");
for(int   I   =   0;   I   <   20;   ++I){
ps.setInt(1,I);
        ResultSet   rs   =   ps.executeQuery();
        System.out.println( "--------------- "+(System.currentTimeMillis()-l));
        l   =   System.currentTimeMillis();
}
System.out.println( "------------------------------------- "   +   (System.currentTimeMillis()-l3));

}catch(Exception   e){}
打印出来的结果如下:
---------------829
---------------375
---------------0
---------------1140
---------------1391
---------------3187
---------------1907
---------------4000
---------------62
---------------1156
---------------125
---------------1485
---------------0
---------------0
---------------0
---------------235
---------------468
---------------27485
---------------1844
---------------562
-------------------------------------46266
---------------875
---------------359
---------------0
---------------1219
---------------1344
---------------2750
---------------1969