JDBC连接数据库使用PreparedStatement批量插入

jdbc.properties

user =root
password =123456
url =jdbc:mysql://localhost:3306/demo?useUnicode=true&&characterEncodeing=UTF-8&&useSSL=false&&serverTimezone=GMT&&rwriteBatchedStatments=true
driverClass =com.mysql.cj.jdbc.Driver

JdbcUtils.java

    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        String user= properties.getProperty("user");
        String password =  properties.getProperty("password");
        String url = properties.getProperty("url");
        String driverClass = properties.getProperty("driverClass");
        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(url,user,password);
        return connection;
    }
public static void closeResource(Connection connection, PreparedStatement ps){
        try {
            if (ps!=null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (connection!=null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

test.java

 @Test
    public void Inserts(){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            long start = System.currentTimeMillis();
            //获取数据库连接
            conn = JdbcUtils.getConnection();
            //设置不允许自动提交数据
            conn.setAutoCommit(false);
            String sql = "insert into tab(id) value(?)";
            ps = conn.prepareStatement(sql);
            for (int i=0;i<1000;i++){
                ps.setInt(1,i);
                //积累sql
                ps.addBatch();
                if (i%500 ==0){
                    //执行batch
                    ps.executeBatch();
                    //清空batch
                    ps.clearBatch();
                }
            }
            //提交数据
            conn.commit();
            long end = System.currentTimeMillis();
            System.out.println("运行时间:"+(end-start));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JdbcUtils.closeResource(conn,ps);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的使用JDBC连接PostgreSQL数据库进行批量插入的Java代码示例: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class BatchInsertDemo { public static void main(String[] args) { String url = "jdbc:postgresql://localhost:5432/mydb"; String username = "username"; String password = "password"; Connection conn = null; PreparedStatement ps = null; try { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); String sql = "INSERT INTO mytable (id, name) VALUES (?, ?)"; ps = conn.prepareStatement(sql); for (int i = 1; i <= 1000; i++) { ps.setInt(1, i); ps.setString(2, "name" + i); ps.addBatch(); } int[] result = ps.executeBatch(); conn.commit(); System.out.println("Inserted " + result.length + " records successfully!"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); try { if (conn != null) { conn.rollback(); } } catch (SQLException ex) { ex.printStackTrace(); } } finally { try { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 在上面的代码示例中,我们假设有一张名为 `mytable` 的表,包含 `id` 和 `name` 两个字段。我们要将1000条记录批量插入到该表中。首先,我们使用 `DriverManager` 获取数据库连接,并关闭自动提交事务。然后,我们定义了一个SQL插入语句,并使用 `PreparedStatement` 对象进行批量参数设置和批量插入操作。最后,我们在try-catch-finally块中处理异常,并提交或回滚事务,最终关闭连接和预编译语句对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值