JAVA原生JDBC代码实现表记录批量插表保存

2024-01-09 12:45:05
package pub.qingyun;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author CQY
 * @version 1.0
 * @date 2024/1/9 10:11
 **/
public class TestBatchSaveDemo {

    private static final Integer SUBMIT_NUM = 5000;
    private static String url = "";
    private static String password = "";
    private static String username = "";

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(url, username, password);
            // 关闭自动提交
            conn.setAutoCommit(false);
            String sql = "insert into t_user (id ,name, ...) valuse (? ,? ,...)";
            ps = conn.prepareStatement(sql);
            int count = 0;
            for (int i = 0; i < 200000; i++) {
                ps.setString(1, "***");
                ps.setString(2, "***");
                ps.setString(3, "***");
                // ...
                ps.addBatch();
                count++;
                if (count % SUBMIT_NUM == 0) {
                    ps.executeBatch();
                    ps.clearBatch();
                    System.out.println("count:" + count);
                }
            }
            ps.executeBatch();
            ps.clearBatch();
            conn.commit();
            System.out.println("Done!");
        } catch (Exception e) {
            try {
                // 报错回滚
                assert conn != null;
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

文章来源:https://blog.csdn.net/piaoyunlive/article/details/135473821
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。