java使用异步多线程执行插入数据库代码
时间: 2023-10-15 20:06:59 浏览: 196
以下是一个使用线程池异步插入数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncInsertDemo {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "password";
private static final String INSERT_SQL = "INSERT INTO user(name, age) VALUES(?, ?)";
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10); // 创建线程池
try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) {
for (int i = 0; i < 100; i++) {
String name = "user" + i;
int age = i % 50 + 20;
executor.submit(() -> {
try {
PreparedStatement ps = conn.prepareStatement(INSERT_SQL);
ps.setString(1, name);
ps.setInt(2, age);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
executor.shutdown(); // 关闭线程池
}
}
}
```
该代码使用了Java内置的线程池框架Executor,创建了一个固定大小的线程池,然后提交100个插入任务到线程池中执行。每个插入任务都会创建一个PreparedStatement对象,设置参数并执行插入操作。最后关闭线程池。
阅读全文