本文为您介绍如何通过JDBC将数据高效的写入Hologres。
使用限制
通过JDBC写入数据至Hologres需要使用42.2.18及以上的Postgres JDBC Driver。
注意事项
- 使用JDBC连接Hologres后,如果您需要测试写入数据的性能,建议使用VPC网络。公共网络由于自身原因,无法达到性能测试的目标。
- Hologres当前不支持在一个事务中多次写入,因此需要设置autoCommit为true(JDBC的autoCommit默认为true),不要显示的在代码里面进行Commit动作。
如果出现
ERROR: INSERT in transaction is not supported now
报错,则需要设置autoCommit为true。Connection conn = DriverManager.getConnection(url, user, password); conn.setAutoCommit(true);
通过JDBC连接Hologres
示例
使用JDBC写入数据至Hologres的完整示例,语句如下。
package test;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class WriteHolo {
private static void Init(Connection conn) throws Exception {
try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists test_tb;");
stmt.execute("create table if not exists test_tb(pk bigint primary key, f1 text, f2 timestamptz, f3 float);");
}
}
private static void WriteBatchWithPreparedStatement(Connection conn) throws Exception {
try (PreparedStatement stmt = conn.prepareStatement("insert into test_tb values (?,?,?,?)")) {
int batchSize = 256;
for (int i = 0; i < batchSize; ++i) {
stmt.setInt( 1, 1000 + i);
stmt.setString( 2, "1");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse("1990-11-11 00:00:00");
stmt.setTimestamp( 3, new java.sql.Timestamp(parsedDate.getTime()));
stmt.setDouble( 4, 0.1);
stmt.addBatch();
}
stmt.executeBatch();
}
}
private static void InsertOverwrite(Connection conn) throws Exception {
try (PreparedStatement stmt = conn.prepareStatement("insert into test_tb values (?,?,?,?), (?,?,?,?), (?,?,?,?), (?,?,?,?), (?,?,?,?), (?,?,?,?) " +
"on conflict(pk) do update set f1 = excluded.f1, f2 = excluded.f2, f3 = excluded.f3")) {
int batchSize = 6;
for (int i = 0; i < batchSize; ++i) {
stmt.setInt(i * 4 + 1, i);
stmt.setString(i * 4 + 2, "1");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse("1990-11-11 00:00:00");
stmt.setTimestamp(i * 4 + 3, new java.sql.Timestamp(parsedDate.getTime()));
stmt.setDouble(i * 4 + 4, 0.1);
}
int affected_rows = stmt.executeUpdate();
System.out.println("affected rows => " + affected_rows);
}
}
public static void main(String[] args) throws Exception {
Class.forName("org.postgresql.Driver").newInstance();
String host = "127.0.0.1:13737";
String db = "postgres";
String user = "xx";
String password = "xx";
String url = "jdbc:postgresql://" + host + "/" + db+"?reWriteBatchedInserts=true";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
Init(conn);
WriteBatchWithPreparedStatement(conn);
InsertOverwrite(conn);
}
}
}
在文档使用中是否遇到以下问题
更多建议
匿名提交