jdbc查询mysql与直接在客户端上查询慢很多

 /**
     * 获取statement对象,操作数据库,处理返回结果
     * */
    public static void process() {
        System.out.println("------- " + System.currentTimeMillis());
        Connection con = getConnection();
        System.out.println("------- " + System.currentTimeMillis());
        PreparedStatement ps = null;
        ResultSet rs = null;
        long current = System.currentTimeMillis();
        System.out.println("------   "  + current);
        String sql = "select user_id from (select t.user_id, sum(case when type='fundmoney' then t.cny else 0 end) as fundcny, \n" +
                "sum(case when type='withdrawmoney' then -t.cny else 0 end) as withdrawmoney from userdata t1 inner join `transaction` t \n" +
                "on t1.user_id = t.user_id and t.type in ('fundmoney','withdrawmoney') where t.type in ('fundmoney','withdrawmoney') \n" +
                "and substring(t1.id_number,7,4) >= 1993 and length(t1.id_number) = 18 and t1.id_number_status in (2,3,4,9,10) and t1.id_type = 1 \n" +
                " group by t1.user_id) t where fundcny >= 100000 or withdrawmoney >= 100000";
        try {
            ps = con.prepareStatement(sql);
            ps.setFetchSize(1000);
            System.out.println("开始查询");
            if (ps.execute()) {
                rs = ps.getResultSet();
                System.out.println("---查询时间---   "  + (System.currentTimeMillis() - current) / 1000);
            } else {
                int i = ps.getUpdateCount();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
    }

这个查出来需要 170秒
但是直接把sql弄到客户端上查只要7秒,已经确定没有查询缓存。

统一回复一下, 不是说SQL慢的问题,而是说用jdbc执行同一个SQL 执行时间却变慢了,30倍的差距, 所以找sql的原因我真不知道应该怎么回答,
试过简单的SQL,在客户端上只要300ms 但是用jdbc需要3s 也是10倍的差距, 已经确定不是因为连接时的原因,
就是在executeQuery的时候的问题。

你确定要170秒?!

对啊。。 确定。。。 肯定。。 我已经弄了好多次了。。 都是如此

单位是ms,不是s吧,首先 每一次的jdbc连接都是一次io操作,比较耗费性能,而且你设置每次最多抓取1000条数据,如果数据量过大,这可能导致频繁的io操作,而你直接在客户端中查询时不需要jdbc连接耗性能的。也是小白,多多指教.

将PreparedStatement 改为Statement

dbu = new DBUtil();  
preStmt = dbu.getConnection().createStatement();  
rs = preStmt.executeQuery(sql.toString());  

楼主可能忽略了一个问题,客户端查出来的只是部分数据(界面没显示全部数据,其实就是查了部分),而你用程序查的是全部数据。

你所谓的客户端是SQL可视化工具么?如果是可以看看这篇文章http://quicker.iteye.com/blog/2291101

应该数据库字段没有加索引导致的,给每个表出现的字段加上索引试试

写一个DbUtil.java 组件试试

如果想提高查询效率可以通过创建索引和创建视图的方式提高

统一回复一下, 不是说SQL慢的问题,而是说用jdbc执行同一个SQL 执行时间却变慢了,30倍的差距, 所以找sql的原因我真不知道应该怎么回答,
试过简单的SQL,在客户端上只要300ms 但是用jdbc需要3s 也是10倍的差距, 已经确定不是因为连接时的原因,
就是在executeQuery的时候的问题。

问题有解决吗? 我也遇到了 同样的问题 ,都是查count 有10倍的差距