java clickhouse 批量插入随机数据
时间: 2023-07-06 20:05:30 浏览: 191
java实现jdbc批量插入数据
你可以使用Java的ClickHouse JDBC驱动程序来批量插入随机数据。
以下是一个示例代码,它将生成一些随机数据并将其批量插入到ClickHouse数据库中:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
public class ClickHouseBatchInsert {
private static final String CLICKHOUSE_URL = "jdbc:clickhouse://localhost:8123/mydb";
private static final String CLICKHOUSE_USER = "default";
private static final String CLICKHOUSE_PASSWORD = "";
private static final int BATCH_SIZE = 10000;
private static final int NUM_ROWS = 1000000;
public static void main(String[] args) throws SQLException {
// Open a connection to ClickHouse database
Connection conn = DriverManager.getConnection(CLICKHOUSE_URL, CLICKHOUSE_USER, CLICKHOUSE_PASSWORD);
// Generate random data
Random rand = new Random();
String[] names = {"Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"};
String[] countries = {"USA", "China", "India", "Brazil", "Russia", "Japan"};
String[] jobs = {"Engineer", "Manager", "Analyst", "Salesperson", "Designer", "Programmer"};
// Prepare the insert statement
PreparedStatement stmt = conn.prepareStatement("INSERT INTO mytable (name, age, country, job) VALUES (?, ?, ?, ?)");
// Insert the data in batches
for (int i = 0; i < NUM_ROWS; i++) {
// Set the parameters for the insert statement
stmt.setString(1, names[rand.nextInt(names.length)]);
stmt.setInt(2, rand.nextInt(50) + 20);
stmt.setString(3, countries[rand.nextInt(countries.length)]);
stmt.setString(4, jobs[rand.nextInt(jobs.length)]);
// Add the insert statement to the batch
stmt.addBatch();
// Execute the batch when it reaches the batch size
if ((i + 1) % BATCH_SIZE == 0) {
stmt.executeBatch();
}
}
// Execute any remaining statements in the batch
stmt.executeBatch();
// Close the statement and connection
stmt.close();
conn.close();
}
}
```
这个示例代码中,我们使用了ClickHouse数据库的JDBC驱动程序来连接到数据库。然后,我们使用Java的随机数生成器来生成一些随机数据,并将其插入到ClickHouse数据库中。我们使用批量插入的方式来提高插入性能,每次插入10000行数据。最后,我们关闭了连接和语句对象。
你只需要将代码中的表名、列名和ClickHouse数据库的连接信息修改为你自己的即可。
阅读全文