需求:最近接手公司的统计工程,发现本地数据库中没有一条数据,就让我的上司给我倒出了最近几天的sql脚步,10M左右,比起的要小多了;然而导入时怎么也无法导入,查看之后才发现,全部数据形式不带表名
INSERT INTO (id, stat_date, referrer, func, catid, user_type, action_stat, channel) VALUES (240092, "2012-3-6", "renren.com", -10, 11611, -10, 65:4.0;57:1.0;52:1.0", "-10");INSERT INTO (id, stat_date, referrer, func, catid, user_type, action_stat, channel) VALUES(240093, "2012-3-6", "baidu.com", -1, 10587, -10, "65:273.0", "-10");总共6万多条;如果一个个加表名要多久呀,立即想到用程序处理一下,我们只要VALUES的值,使用sql批量插入就可以实现;
根据sql脚本的形式,我们只需要将VALUES后面括号后的“;”换成逗号,最终形式为
(240092, "2012-3-6", "renren.com", -10, 11611, -10, "65:4.0;57:1.0;52:1.0", "-10"), (240093, "2012-3-6", "baidu.com", -1, 10587, -10, "65:273.0", "-10"), (240094, "2012-3-6", "baidu.com", -1, 10589, -10, "65:1040.0;57:6.0;52:10.0", "-10"), (240095, "2012-3-6", "qq.com", -10, 11913, -10, "65:1.0", "channelId_846"), (240096, "2012-3-6", "baidu.com", -1, 10581, -10, "65:1423.0;57:5.0;52:5.0", "-10"), (240097, "2012-3-6", "baidu.com", -1, 10583, -10, "57:20.0;52:23.0;65:2823.0", "-10"),这样我们只需要在转换后的脚本文件开头加上
INSERT INTO t_xxx (id, stat_date, referrer, func, catid, user_type, action_stat, channel)VALUES即可以批量插入数据库;下面是JavaIO处理程序;
public static void main(String[] args) throws Exception{ BufferedReader in =new BufferedReader(new FileReader("D:\\sql.sql"));//要读取的文本文件 BufferedWriter br=new BufferedWriter(new FileWriter("D:\\aaa.sql"));//输出的结果文件 String s = ""; Pattern pattern = Pattern.compile(".*[)][;]");//正则匹配sql结尾 Matcher m = null;int i = 1;while((s = in.readLine()) != null){ m = pattern.matcher(s); if(m.matches()){ System.out.println(i++); s = s.replace(");", "),");//替换 }if(!s.matches(" *")){//剔除空白行 br.write(s); br.write("\n"); } }//关闭 in.close(); br.flush(); br.close(); }执行速度很快,大约不到2秒;接下来又有问题了,不是这个sql脚步有问题,而是因为6-7W条数据一次插入,mysql不能处理;自己写jdbc可以实现,不过又要读取这个导出的可执行脚本文件,那就干脆手动插入吧,一次考1-2W条,把
INSERT INTO t_xxx (id, stat_date, referrer, func, catid, user_type, action_stat, channel) VALUES加到数据开头,5次也插完了;
转载于:https://www.cnblogs.com/wufengxyz/archive/2012/03/09/2388214.html
相关资源:数据结构—成绩单生成器