在MysqL中,可以使用LOAD DATA INFILE和LOAD DATA LOCAL INFILE两种方式导入文本文件中的数据到数据库表中,速度非常快。其中LOAD DATA INFILE使用的文件要位于MysqL所在服务器上,LOAD DATA LOCAL INFILE则使用的是客户端的文件。
LOAD DATA INFILE 'data.txt' INTO TABLE table_name;
LOAD DATA LOCAL INFILE 'data.txt' INTO TABLE table_name;
在Postgresql中也可以导入相同类型的文本文件,使用的是COPY命令:
COPY table_name FROM 'data.txt';
但是这个语句只能导入Postgresql所在服务器上的文件,要想导入客户端文件,就需要使用下面的语句:
COPY table_name FROM STDIN;
在Java中,可以通过设置流的方式,设置需要导入的客户端本地文件。
public void copyFromFile(Connection connection,String filePath,String tableName)
throws sqlException,IOException {
FileInputStream fileInputStream = null;
try {
CopyManager copyManager = new CopyManager((BaseConnection)connection);
fileInputStream = new FileInputStream(filePath);
copyManager.copyIn("COPY " + tableName + " FROM STDIN",fileInputStream);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
另外,还可以使用COPY table_name TO STDOUT来导出数据文件到本地,和上面的导入相反,可以用于数据库备份。此外,还支持导出一个SQL查询结果:
COPY (SELECT columns FROM table_name WHERE ……) TO STDOUT;
Java代码如下:
public void copyToFile(Connection connection,String tableOrQuery)
throws sqlException,IOException {
FileOutputStream fileOutputStream = null;
try {
CopyManager copyManager = new CopyManager((BaseConnection)connection);
fileOutputStream = new FileOutputStream(filePath);
copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT",fileOutputStream);
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用方式:
// 将本地d:/data.txt文件中的数据导入到person_info表中
copyFromFile(connection,"d:/data.txt","person_info");
// 将person_info中的数据导出到本地文件d:/data.txt
copyToFile(connection,"person_info");
// 将SELECT p_name,p_age FROM person_info查询结果导出到本地文件d:/data.txt
copyToFile(connection,"(SELECT p_name,p_age FROM person_info)");
相关文章
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250