0

大家好!

开门见山。是否有任何 java 库可以从 DB 生成 Postgres SQL 脚本?

例如我有表 job_table

   name    | job
   Andy    | pull
   Benny   | push

然后,我想像这样得到 String sql-script

String sqlInsert = 

  "INSERT INTO job_table(name, job) VALUES ('Andy', 'pull');"+
  "INSERT INTO job_table(name, job) VALUES ('Benny', 'push');";

或者类似的东西。

有人知道吗?

注意:我已经用 java 编写了自己的代码来手动生成它。但我就是不喜欢。:)

之前谢谢。

4

1 回答 1

2

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.

于 2012-04-23T07:23:53.813 回答