用prepareStatement 设置参数,速度超级慢,还不如直接拼接字符串,有人能告诉我为什么吗?

解决方案 »

  1.   

    同样的数据条件下肯定prepareStatement要快,不知LZ为何这般慢
    能否把你的SQL部分贴出来?
      

  2.   

    Connection connection = getConn();
    PreparedStatement ps = null;
    ResultSet records = null;
    try {
    String hql = "select * from (select rownum rid,m.* from " +
    "(select t.vehiclelsh,t.plateinfo,t.platetype,t.passtime,t.vehiclespeed from bayonet_vehiclepass t" +
    " where passtime>to_date('012-2-25 0:00:00','yyyy-MM-dd hh24:mi:ss') and passtime < to_date('2012-7-25 0:00:00','yyyy-MM-dd hh24:mi:ss')" +
    " and vehiclespeed > ?  and vehiclespeed < ? order by passtime desc) m    where rownum < 35464 ) s where s.rid > 35453";
    List param = new  ArrayList();
    param.add(0);
    param.add(200);
    String hql1 = "select count(*) from bayonet_vehiclepass";
    ps = connection.prepareStatement(hql);
    int i = 0;
    for (Object object : param) {
    i++;
    ps.setObject(i, object);
    }
    Long l1 = System.currentTimeMillis();
    records = ps.executeQuery();
    System.out.println(System.currentTimeMillis()-l1);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    closeConn(ps, records, connection);
    }

    我这边只设置两个参数就很慢了,如果把时间也设置上去就更慢了,要13秒左右,如果用拼接字符串就只要不到1秒
      

  3.   

    for (Object object : param) {
    i++;
    ps.setObject(i, object);
    }
      

  4.   

    能用prepareStatement就一定要用 ,尽量少用字符串拼接,假设有一个发表文章的场景,文章的内容通过编辑器会带有各种样式,所以真正插入到数据库里的是HTML的代码,会带有许多单引号,如果使用字符串拼接的话这些单引号会改变sql语句的原意,从而造成插入失败。
    同时,如果有人刻意提交恶意表单来改变你sql语句的原意,就会查询出你数据库里的一些保密的信息,这就是sql注入。
      

  5.   

    只知道prepareStatement一般比拼接快
    为什么你的会这么慢 等高手。