如何使用 JDBC 将数据从文件复制到 PostgreSQL? [英] how to copy data from file to PostgreSQL using JDBC?
本文介绍了如何使用 JDBC 将数据从文件复制到 PostgreSQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 JDBC 将数据从文件复制到 PostgreSQL DB.我正在使用 JDBC 语句对象将文件复制到数据库中.很慢.
I want to copy data from file to PostgreSQL DB using JDBC. I was using JDBC statement object to copy the file into DB. It is very slow.
我开始知道我们也可以使用 copy out 命令将文件复制到数据库.但是,我怎么能用 JDBC 做到这一点.即使是在 JDBC 中提供复制示例的良好参考材料也会有所帮助.
I came to know that we can also use copy out command to copy file to DB. But, how can I do that with JDBC. Even good reference material having an example of copy in JDBC would help.
PS:提前致谢
推荐答案
这有效...
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.");
}
}
}
这篇关于如何使用 JDBC 将数据从文件复制到 PostgreSQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文