可以使用多线程来实现向数据库插入数据。以下是一个简单的示例代码:

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

public class InsertDataThread extends Thread {
    private final int batchSize;
    private final int start;
    private final int end;
    private final String url;
    private final String username;
    private final String password;

    public InsertDataThread(int batchSize, int start, int end, String url, String username, String password) {
        this.batchSize = batchSize;
        this.start = start;
        this.end = end;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    @Override
    public void run() {
        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false);

            String sql = "INSERT INTO your_table_name (column1, column2) VALUES (?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);

            for (int i = start; i <= end; i++) {
                statement.setInt(1, i);
                statement.setString(2, "data " + i);
                statement.addBatch();

                if (i % batchSize == 0) {
                    statement.executeBatch();
                }
            }

            statement.executeBatch();
            connection.commit();

            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        int totalDataCount = 10000;
        int batchSize = 1000;
        int threadCount = totalDataCount / batchSize;

        String url = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";

        for (int i = 0; i < threadCount; i++) {
            int start = i * batchSize + 1;
            int end = (i + 1) * batchSize;
            Thread thread = new InsertDataThread(batchSize, start, end, url, username, password);
            thread.start();
        }
    }
}

上述代码中,通过创建多个线程来向数据库插入数据。每个线程负责插入一段数据范围内的数据。可以根据需要调整数据库连接的参数、SQL语句和数据范围等

Java 有10000条数据每次向数据库插入1000条数据如何用线程插入

原文地址: https://www.cveoy.top/t/topic/iQC3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录