JAVA: mysql/oracle 导入导出文件
前段时间做了个需求,需要实现把Oracle、mysql的数据导入到mysql的功能。
一、 mysql导出文件
1. 导出csv文件,我选择的是使用mysql命令:
mysql -hxx -Pxx -uxx -pxx -Dxx -N --default-character-set=utf8 -e "select CONCAT_WS(,,id,name) from test;" > D: est mp.csv
-
-N是指不导出字段名称 编码使用utf8 使用CONCAT_WS函数将字段用逗号分隔,如果不分隔,一条数据就会在一个单元格中
2. java程序调用,使用Runtime.getRuntime().exec(命令)
String[] cmds = null; if(linux) { cmds = new String[] { "sh", "-c", cmd }; }else if (windows){ cmds = new String[] { "cmd", "/c", cmd }; } Process ps = Runtime.getRuntime().exec(cmds);
-
判断系统可以使用
String osName = System.getProperties().getProperty("os.name"); if (osName.toLowerCase().startsWith("linux")) { return true; } else { return false; }
-
在linux系统执行,需要使用 “sh -c 命令”;Windows系统执行,需要使用“cmd /c 命令” 参考了
二、oracle导出文件
1. 使用sqluldr2命令
sqluldr2 user=用户名/密码@ip:1521/服务 query="select * from test" head=no file=D: est est.csv charset=UTF8 field=,
-
head=no 不导出字段名称 编码 charset=UTF8 field=, 字段分隔符使用逗号 安装包下载及使用参考了:
2. java程序调用与上面一样
三、mysql导入文件
1. 使用mysql语句 LOAD DATA
-
参考:
四、遇到的各种坑
1. load date的权限问题
2. mybatis执行load data时报错 MySqlLoadDataInFileStatement not allow
看到有的文章说需要在数据库链接后拼上&allowLoadLocalInfile=true,我试了试并不起作用,后来想起来项目使用的多数据源Druid,找到了这篇
顺藤摸瓜找到了拦截配置,其中:
把这个配置改为true就可以正常执行了。
修改方式:在Druid配置类中设置noneBaseStatementAllow
@Bean public WallFilter wallFilter() { WallFilter wallFilter = new WalFilter(); wallFilter.setConfig(wallConfig()); return wallFilter; } @Bean pubLic WallConfig wallConfig() { WallConfig config = new WallConfig(); config.setNoneBaseStatementAllow(true);//允许非基本语句的其他语句 return config; } List<Filter> filterList = new ArrayList<>(); filterList.add(wallFilter()); datasource.setProxyFilters(filterList); datasource.setFilters("stat");//不加wall
3. 导出字段的值中含有逗号,的情况,在导入数据时字段位置发生错乱
一个简单的处理方式,将分隔符设置复杂些,减小分隔符出现在字段值中的概率