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

Red*_*ddy 14 java database postgresql jdbc jdbctemplate

我想使用JDBC将数据从文件复制到PostgreSQL DB.我正在使用JDBC语句对象将文件复制到DB中.这很慢.

我才知道我们也可以使用copy out命令将文件复制到DB.但是,我如何处理JDBC.即使是在JDBC中具有复制示例的好的参考资料也会有所帮助.

PS:提前谢谢

ali*_*ips 30

这有效......

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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 强制转换`(BaseConnection)con`可能无效;在某些情况下,连接会被包装为其他某种连接类型(例如,使用连接池或间谍时)。对我有用的是改为使用`con.unwrap(BaseConnection.class)`。 (2认同)