zoukankan      html  css  js  c++  java
  • JDBC 批处理

    public class BatchTest {

        /**
         * @param args
         * @throws SQLException
         */
        public static void main(String[] args) throws SQLException {
            long start = System.currentTimeMillis();
            for (int i = 0; i < 100; i++)
                create(i);
            long end = System.currentTimeMillis();
            System.out.println("create:" + (end - start));

            start = System.currentTimeMillis();
            createBatch();
            end = System.currentTimeMillis();
            System.out.println("createBatch:" + (end - start));
        }

        static void create(int i) throws SQLException {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = JdbcUtils.getConnection();
                String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";
                ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, "no batch name" + i);
                ps.setDate(2, new Date(System.currentTimeMillis()));
                ps.setFloat(3, 100f + i);

                ps.executeUpdate();
            } finally {
                JdbcUtils.free(rs, ps, conn);
            }
        }

        static void createBatch() throws SQLException {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = JdbcUtils.getConnection();
                String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";
                ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                for (int i = 0; i < 100; i++) {
                    ps.setString(1, "batch name" + i);
                    ps.setDate(2, new Date(System.currentTimeMillis()));
                    ps.setFloat(3, 100f + i);

                    ps.addBatch();//sql语句封包一起发送到数据库服务器
                }
                int[] is = ps.executeBatch();
            } finally {
                JdbcUtils.free(rs, ps, conn);
            }
        }
    }

  • 相关阅读:
    [转帖]ExtJs与服务器的交互(一)
    Ext_两种处理服务器端返回值的方式
    命令行调用dubbo远程服务
    【转】Lombok Pojo默认初始值问题
    【转】Python之可变参数,*参数,**参数,以及传入*参数,进行解包
    Python获取并输出当前日期时间
    idea上 实现了Serializable接口,要自动生成serialVersionUID的方法
    mac下python2.x和python3.x的安装方法和升级方法/卸载
    工程代码不编译src的java目录下的xml文件问题及解决
    Spring Aop织入点语法
  • 原文地址:https://www.cnblogs.com/flying607/p/3462315.html
Copyright © 2011-2022 走看看