Use the PgJDBC support for the COPY command to feed tab-delimited or CSV data into the database, and to extract it in the same format. You want the CopyManager, which can be obtained from a PgConnection.
The CopyManager is rather woefully under-documented at present, but it's just a wrapper around the COPY
command.
Get access to the PgConnection
interface by casting your java.sql.Connection to PgConnection
. If the connection is wrapped by a connection pooling service you may have to unwrap it to get the real underlying connection returned by PgJDBC. Same deal if you're using JPA, you'll have to get access to the real PgJDBC connection or make a new one.
If you actually need INSERT
statements, rather than an efficient way of delivering data to the database, what are your specific needs? Portability? If so, how will you handle things like the different representations of NUMERIC / DECIMAL / whatever?
If you only need to handle the "standard" data types, your hand rolled code may be the best way.
The only strictly safe way to do that is currently via pg_dump. You can invoke a pg_dump --data-only --table=thetable
process and read from its stdout to do the job, though this does require (a) direct knowledge of the DB details in the app, not just a DataSource or injected entity manager from a container; (b) knowledge of the pg_dump path, and (c) the security permission to execute external processes. Unfortunately there isn't really any way around that at present. pg_dump isn't designed to be used as a library (though there's been talk of converting it) and even if it were, it'd be a C library you'd have to wrap via JNI or similar. Ick.