今天碰到数据库迁移的问题,从mysql数据库迁移到db2数据库,首先尝试了 ibm 的ibm_mtk_V2_win进行数据迁移,可是狗血的出现了不少问题(这个只支持java6,版本过高记得换回来) 后来想到了写脚本(主要是一个sql有一两百兆的数据,复制粘贴执行不可行)java
package com.hsm.db; import java.io.*; import java.sql.*; /** * 读取指定文件下sql脚本,执行到数据库 * 朱行读取分批处理批量插入数据库 */ public class TestReadFile { public static void main(String[] args) { System.err.println("begin"); long start = System.currentTimeMillis(); String path = "C:\\Users\\huangsm@allinfinance.com\\Desktop\\tm_account.sql"; getData(path); System.err.print((System.currentTimeMillis() - start) / 1000); } private static void getData(String path) { //读取文件 BufferedReader reader; Connection conn = null; Statement pst = null; try { Class.forName("com.ibm.db2.jcc.DB2Driver"); conn = DriverManager.getConnection( "jdbc:db2://10.250.1.211:50000/zyjr:currentSchema=C;","zyjr","zyjr"); System.out.println("数据库链接成功!!!"); pst = conn.createStatement(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String line; int i = 0; while ((line = reader.readLine()) != null) { //主要防止空行问题,我的以为这样比简单 if(line.length()<=10){ continue; } if(i==0){ //这个执行的时候发现的问题,不知道为何,用这个测试 System.out.println(line); pst.execute(line.substring(1,line.length()-1)); }else{ System.out.println(line); pst.execute(line.substring(0,line.length()-1)); } if (i % 100 == 0) { System.out.println("执行了:" + i); } i += 1; } reader.close(); // 执行批量更新 } catch (Exception e) { e.printStackTrace(); } finally { try { if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
写完以后被一个家伙说,这样写数据库插入太慢了,我就呵呵了,毕竟花了这么长时间,最好告诉我能够写sh脚本,并且还提供了sh脚本案例,我就开心的换了一个方式.(工做就是好,能够互相的交流)mysql
#!/bin/sh echo "--------------------------------- cts数据初始化 START----------------------------" db2 connect to zyjrdb user zyjrusr using zyjrusr db2 set schema=CTS #插入数据 #db2 -tvf tm_account.sql db2 -tvf tm_address.sql db2 -tvf tm_card.sql db2 -tvf tm_contact_tel.sql db2 -tvf tm_contract.sql db2 -tvf tm_customer.sql db2 -tvf tm_repayment.sql #db2 -tvf tm_period.sql db2 connect reset echo "--------------------------------- cts 数据初始化 END ----------------------------"
这个脚本很简单,主要就是把数据执行写在了一块儿,还有执行脚本的时候必定要让脚本具备可执行权限,语句为sql
chmod +x fielname #具体细节能够看书
这个时候想起了一句话:入了行,什么都简单了数据库