有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用JDBC将数据从文件复制到PostgreSQL?

我想使用JDBC将数据从文件复制到PostgreSQL数据库。我使用JDBC语句对象将文件复制到DB中。它非常慢

我知道我们也可以使用copyout命令将文件复制到数据库。但是,我如何用JDBC做到这一点呢。即使是好的参考资料,在JDBC中有一个复制的例子也会有所帮助

PS:提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    这很有效

    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.");
            }
        }
    }
    
  2. # 2 楼答案

    (基于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