postgresql - 如何使用 jdbc API 在 java 中为 postgresql 数据库执行 sql gzipped 脚本?

标签 postgresql jdbc gzip

我想使用 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/

相关文章:

javascript - AJAX 不返回 JSP 形式的值

javascript 优化和缩小 vs. gzipping

python - 当生成的表不够时,编写自己的表创建 SQL 以与 Django 一起使用是否安全?

sql - 在 PostgreSQL 中对 NULL 值进行排序

Asp.NET Core 后台服务应用

mysql - 数据库设计 : Associating tables of variable types

Java - 如何获取结果集上的列名

java - JSP 的 <% %> 与 <? ?> 对于 PHP?

python - 发送压缩后的表单数据

内存中的python gzip文件并上传到s3