【问题标题】:how to copy data from file to PostgreSQL using JDBC?如何使用 JDBC 将数据从文件复制到 PostgreSQL?
【发布时间】:2011-10-20 23:58:49
【问题描述】:

我想使用 JDBC 将数据从文件复制到 PostgreSQL 数据库。我正在使用 JDBC 语句对象将文件复制到数据库中。速度很慢。

我知道我们也可以使用 copy out 命令将文件复制到数据库。但是,我怎么能用 JDBC 做到这一点。即使是包含 JDBC 副本示例的优秀参考资料也会有所帮助。

PS:提前谢谢

【问题讨论】:

  • 向我们展示代码,我们可能会解释为什么它很慢。特别是,您是否使用批量更新?你在使用准备好的语句吗?
  • 是的,我正在批量更新。

标签: java database postgresql jdbc jdbctemplate


【解决方案1】:

(基于aliasmrchips' 的回答:)如果你有一个 Groovy 环境(就像我在 ANT 中使用它一样),你可以这样做像这样(用 Postgres 代替 Oracle 的细节):

// exec.groovy
this.class.classLoader.rootLoader.addURL('${postgres-jdbc-driver-path}')
PgScript.load()

// PgScript.groovy
// (we cannot use the org.postgres.* classes in exec.groovy already!)
import java.io.FileReader
import java.sql.DriverManager
import org.postgresql.copy.CopyManager
import org.postgresql.core.BaseConnection

class PgScript {
    static void load() {        

        DriverManager.getConnection (
            '${jdbc-db-url}', '${db-usr}', '${db-usr-pass}'
        ).withCloseable {conn ->
            new CopyManager((BaseConnection) conn).
                copyIn('COPY t FROM STDIN', new FileReader('${sqlfile}'))
        }
    }
}

也基于此javaworld.com article

【讨论】:

    【解决方案2】:

    这行得通...

    import java.io.FileReader;
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    import org.postgresql.copy.CopyManager;
    import org.postgresql.core.BaseConnection;
    
    public class PgSqlJdbcCopyStreamsExample {
    
        public static void main(String[] args) throws Exception {
    
            if(args.length!=4) {
                System.out.println("Please specify database URL, user, password and file on the command line.");
                System.out.println("Like this: jdbc:postgresql://localhost:5432/test test password file");
            } else {
    
                System.err.println("Loading driver");
                Class.forName("org.postgresql.Driver");
    
                System.err.println("Connecting to " + args[0]);
                Connection con = DriverManager.getConnection(args[0],args[1],args[2]);
    
                System.err.println("Copying text data rows from stdin");
    
                CopyManager copyManager = new CopyManager((BaseConnection) con);
    
                FileReader fileReader = new FileReader(args[3]);
                copyManager.copyIn("COPY t FROM STDIN", fileReader );
    
                System.err.println("Done.");
            }
        }
    }
    

    【讨论】:

    • pedal-dialect 允许您直接对 JPA 实体使用复制命令。
    • 演员(BaseConnection) con 可能不起作用;在某些情况下,连接被包装在其他连接类型中(例如,当使用连接池或间谍时)。对我有用的是改用con.unwrap(BaseConnection.class)
    • 谢谢!似乎这是通过 JDBC 执行此操作的唯一方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多