日期:2014-05-16  浏览次数:20597 次

java程序创建导入,导出,创建数据库
在做项目的时候,往往会遇到数据库创建,备份,还原等功能,java可以很快的实现其功能,具体的代码如下:
package com.hq.tools;
import java.io.*;
public class DBtools {
/**
* 初始化数据库
* @return
*/
public boolean CreateDatabase(){
boolean flag=true;
String[] cmd = new String[] { "cmd.exe", "/C","mysqladmin -u root -proot create yishiyiyi"};
try {
Process process = Runtime.getRuntime().exec(cmd);
new Thread(new StreamDrainer(process.getInputStream())).start();
new Thread(new StreamDrainer(process.getErrorStream())).start();
process.getOutputStream().close();
int exitValue = process.waitFor();
if(exitValue!=0){
flag=false;
}
} catch (Exception e) {
e.printStackTrace();
}

return flag;

}
/**
* 导出数据库脚本,备份用
* @param filename
* @return
*/
public Boolean ExportDatabase(String filename) {
boolean flag=true;
filename="\""+filename+"\"";
String[] cmd = new String[] { "cmd.exe", "/C", "mysqldump -u root -proot yishiyiyi >"+filename+"" };
try {
Process process = Runtime.getRuntime().exec(cmd);
new Thread(new StreamDrainer(process.getInputStream())).start();
new Thread(new StreamDrainer(process.getErrorStream())).start();
process.getOutputStream().close();
int exitValue = process.waitFor();
if(exitValue!=0){
flag=false;
}

} catch (Exception e) {

e.printStackTrace();
}

return flag;

}
/**
* 将数据库脚本导入到数据库
* @param filename
* @return
*/
public static boolean ImportDatabase(String filename){
boolean flag=true;
filename="\""+filename+"\"";
String[] cmd = new String[] { "cmd.exe", "/C", "mysql -u root -proot yishiyiyi <"+filename+"" };

try {
Process process = Runtime.getRuntime().exec(cmd);

new Thread(new StreamDrainer(process.getInputStream())).start();
new Thread(new StreamDrainer(process.getErrorStream())).start();

process.getOutputStream().close();

int exitValue = process.waitFor();
if(exitValue!=0){
flag=false;
}
} catch (Exception e) {
e.printStackTrace();
}

return flag;

}

}