java调用mysql命令导入脚本方案

本文介绍了一种通过Java调用MySQL脚本来实现数据库表及函数创建的方法。由于直接使用Java执行MySQL脚本存在局限性,特别是对于FUNCTION的处理,文章提供了一个解决方案,即先通过mysqldump导出脚本,再利用Java程序合并多个脚本文件,并最终通过MySQL命令行工具执行。

背景:

使用java调用ibatis-common-2.jar中的ScriptRunner类中的runScript方法执行mysql脚本时,表能创建成功,但是FUNCTION没有成功,/!50003…/中注释的内容只有mysql本身的解析器可以执行,其他的程序会忽略掉,所以没有成功。既然只有mysql才能完整的解析脚本,那用mysql本身的命令去执行就好了,本方案才应运而生。以下为范例:

/*Table structure for table `school` */

DROP TABLE IF EXISTS `school`;

CREATE TABLE `school` (
  `schoolId` int(11) NOT NULL AUTO_INCREMENT COMMENT '校区编号',
  `schoolName` varchar(50) NOT NULL COMMENT '校区名称',
   `schoolShortName` varchar(20) DEFAULT NULL COMMENT '校区名称简写'
  PRIMARY KEY (`schoolId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/* Function  structure for function  `f_getSchoolShortName` */

/*!50003 DROP FUNCTION IF EXISTS `f_getSchoolShortName` */;
DELIMITER $$

/*!50003 CREATE FUNCTION `f_getSchoolShortName`(schId int) RETURNS varchar(50) CHARSET utf8
BEGIN
    return(select schoolShortName from school where schoolId=schId);
    END */$$
DELIMITER ;

1.导出

使用命令导出脚本
数据+结构+(函数+存储过程)
mysqldump -hip -uroot -pxxxx –opt -R 数据库名> c:/script.sql

2.合并

package com.thatluck.test.sql;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileReaderUtil {
    public static void main(String[] args) {
        try {
            mergeFile(new File("C:/test"), new File("c:/one/all003.sql"));
            // copyFiles(new File("G:/学习资料/笔记"),new File("G:/Test"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拷贝某个文件目录下面的所有文件,
     * 
     * @param sourcePath
     *            原文件目录
     * @param desPath
     *            目的文件目录
     */
    public static void copyFiles(File sourceFile, File desFile) throws IOException {
        if (sourceFile.isFile()) {
            File file = new File(desFile.getPath() + "/" + sourceFile.getName());
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1)
                fos.write(buf, 0, len);
        } else {
            File dir = new File(desFile.getPath() + "/" + sourceFile.getName());
            if (!dir.exists())
                dir.mkdir();
            String[] names = sourceFile.list();
            for (int i = 0; i < names.length; i++) {
                copyFiles(new File(sourceFile.getPath() + "/" + names[i]), dir);
            }
        }
    }

    /**
     * 将一个文件目录下面的所有文件独到一个文件中的方法(主要用于将很多文本文件合并到一起)
     * 
     * @param sourceFile
     * @param decFile
     * @return
     * @throws IOException
     */
    public static File mergeFile(File sourceFile, File decFile) throws IOException {
        String[] fileList = sourceFile.list();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        File file=null;
        try{
            for (String string : fileList) {
                file = new File(sourceFile.getPath() + "/" + string);
                if (!file.isDirectory()) {
                    fis = new FileInputStream(file);
                    fos = new FileOutputStream(decFile, true);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buffer)) != -1)
                        fos.write(buffer, 0, len);
                } else {
                    decFile = mergeFile(file, decFile);
                }
            }
        }finally{
            fis.close();
            fos.close();
        }
        return decFile;
    }
}

3.导入

/**
 * Administrator
 */
package com.thatluck.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import com.thatluck.test.sql.FileReaderUtil;

/**
 *<p></p>
 *@ClassName:DBTest     
 *@author: thatluck
 *@date:2016年8月5日 上午8:38:16
 *@version: V2.0

 */

public class DBTest {

    /**
     * <p></p>
     * @author thatluck
     * @date 2016年8月5日 上午8:38:16 
     * @param args
     */
    public static void main(String[] args) throws Exception{
        load();
    }
     public static void load() throws Exception{  
         FileReaderUtil.mergeFile(new File("C:/test"), new File("c:/one/all.sql"));
         OutputStream out = null;
         OutputStreamWriter writer = null;
         BufferedReader br = null;
         String fPath = "c:/one/all.sql";   
            try { 
                Runtime rt = Runtime.getRuntime(); 
                // 调用 mysql 的 cmd:   
                Process child = rt.exec(" mysql -hxx.xx.xx.xx -uroot -pxxx  数据苦命");   

                String inStr;   
                StringBuffer sb = new StringBuffer("");   
                String outStr;   
                br = new BufferedReader(new InputStreamReader(   
                        new FileInputStream(fPath), "utf8"));   
                while ((inStr = br.readLine()) != null) {   
                    sb.append(inStr + "\r\n"); 
                    System.out.println(inStr);
                }   
                outStr = sb.toString();   
                out = child.getOutputStream();//控制台的输入信息作为输出流   
                writer = new OutputStreamWriter(out, "utf8");   
                writer.write(outStr);   
                // 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免   
                writer.flush();   
                // 别忘记关闭输入输出流
                System.out.println("/* Load OK! */");   

            } catch (Exception e) {   
                e.printStackTrace();   
            }finally{
            try {
                out.close();
                br.close();
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }  

}

参考:

1.mysqldump导出--数据+结构+(函数+存储过程)
2.Java-合并多个文档到一个文档的Java程序-免费下载
3.java 调用命令 备份mysql数据库【收藏】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值