【发布时间】:2016-01-09 11:00:29
【问题描述】:
我想执行一个使用 java jdbc API 压缩到 postgresql 数据库的 sql 脚本。
我知道如何在 H2 数据库中使用 sql run script 语句来执行此操作。
【问题讨论】:
标签: postgresql jdbc gzip
我想执行一个使用 java jdbc API 压缩到 postgresql 数据库的 sql 脚本。
我知道如何在 H2 数据库中使用 sql run script 语句来执行此操作。
【问题讨论】:
标签: postgresql jdbc gzip
我设法使用此代码对任何数据库执行此操作
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();
}
}
【讨论】:
run script sql命令,它更高效(但需要文件访问)。