我想使用 java jdbc API 执行一个压缩到 postgresql 数据库的 sql 脚本。
我知道如何使用 sql run script 在 H2 数据库中执行此操作声明。
最佳答案
我设法使用此代码对任何数据库执行此操作
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.zip.GZIPInputStream;
/**
* Created on 09/01/16.
*
* @author Tony Chemit - chemit@codelutin.com
*/
public class RunSqlScript {
public void executeSqlScript(Connection connection, boolean gzip, int batchSize, byte... content) throws SQLException, IOException {
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try (BufferedReader reader = createReader(gzip, content)) {
try (Statement statement = connection.createStatement()) {
int currentBatchSize = 0;
String command = null;
String line;
while ((line = reader.readLine()) != null) {
String trimLine = line.trim();
if (trimLine.startsWith("--")) {
continue;
}
command = command == null ? line : command + ' ' + line;
if (trimLine.endsWith(";")) {
statement.addBatch(command);
batchSize++;
command = null;
if (currentBatchSize % batchSize == 0) {
flushStatement(statement);
}
}
}
flushStatement(statement);
}
} finally {
connection.setAutoCommit(autoCommit);
}
}
protected BufferedReader createReader(boolean gzip, byte... content) throws IOException {
return new BufferedReader(new InputStreamReader(new BufferedInputStream(gzip ? new GZIPInputStream(new ByteArrayInputStream(content)) : new ByteArrayInputStream(content))));
}
protected void flushStatement(Statement statement) throws SQLException {
statement.executeBatch();
statement.clearBatch();
}
}
关于postgresql - 如何使用 jdbc API 在 java 中为 postgresql 数据库执行 sql gzipped 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692627/