• 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);
            }
        }
    }

  • 相关阅读:
    如何更改AD域安全策略-密码必须符合复杂性要求
    Flameshot:一个简洁但功能丰富的截图工具
    Linux桌面最轻量的Dock之Plank介绍
    NVIDIA vGPU License服务器搭建详解
    阿姜查 | 当一个人不了解死亡时,生活会非常烦恼
    阿姜查:工作永远没完没了 你为何着急做完?
    .NET 通用高扩展性的细粒度权限管理架构(webApi/Mvc)
    WebApi实现通讯加密 (转)
    MVC
    程序员的沟通之痛
  • 原文地址:https://www.cnblogs.com/flying607/p/3462315.html
Copyright © 2020-2023  润新知