-->

Friday, August 05, 2011

Bulk Inserts with Postgres JDBC COPY

The COPY command is a much faster way to do bulk inserts into a postgres database. The postgres JDBC driver supports this as well.

Here is a simple example of a command line tool to COPY the contents of a text file to a table. Each line becomes a row in the database.


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("usage: [url] [user] [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.");
}
}
}

No comments: