第二种方式:
数据备份:
public class DBBackup {
public static void backup(String DBName,String file){
String user = "root"; // 数据库帐号
String password = "123456"; // 登陆密码
String database = DBName; // 需要备份的数据库名
String filepath = file; // 备份的路径地址
//mysql命令的路径
String mysqlPath="C:/Program Files/MySQL/MySQL Server 5.1/bin/";
try{
Runtime rt = Runtime.getRuntime();
Process child = rt.exec(mysqlPath+"mysqldump -u"+user+" -p"+password+" "+database);
InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader isr = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
// 组合控制台输出信息字符串
BufferedReader br = new BufferedReader(isr);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();//备份出来的内容是一个字条串
FileOutputStream fout = new FileOutputStream(filepath);
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
writer.write(outStr);//写文件
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
in.close();
isr.close();
br.close();
writer.close();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
数据还原:
public class DBUpload {
private static String databases;
static{
QueryBuilder qb=new QueryBuilder("show databases;");
DataTable dt=qb.executeDataTable();
StringBuffer court=new StringBuffer("");
if(dt.getRowCount()>0){
for(int i=0;i
if(i==0){
court.append(dt.getString(i,"Database"));
}else{
court.append(","+dt.getString(i,"Database"));
}
}
databases=court.toString().trim();
}else{
databases="";
}
}
//判断数据库是否已经存在
public static boolean isExist(String DBName){
if(StringUtil.isEmpty(databases)){
return false;
}else{
String dbs[]=databases.split(",");
for(int i=0;i
if(DBName.equalsIgnoreCase(dbs[i])){
return true;
}else{
continue;
}
}
return false;
}
}
public static boolean load(String DBName,String file){
String user = "root"; // 数据库帐号
String password = "mysql"; // 登陆密码
String database = DBName; // 需要备份的数据库名
String filepath=file;
String str1="mysqladmin -u "+user+" -p"+password+" create "+database;
String str2="mysql -u "+user+" -p"+password+" "+database;
try{
if(!isExist(DBName)){//不存在此数据库
Process p=Runtime.getRuntime().exec(str1);
p.waitFor();
}
Process child=Runtime.getRuntime().exec(str2);
OutputStream out = child.getOutputStream();//控制台的输入信息作为输出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br=new BufferedReader(new InputStreamReader( new FileInputStream(filepath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
writer.flush();
// 别忘记关闭输入输出流
out.close();
br.close();
writer.close();
System.out.println("数据导入成功!");
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
}
此方式可以接受命令的路径命中包含空格!!
如果程序出现如后错误:java.io.IOException: 管道已结束
或
java.io.IOException: 管道正在被关闭
可能是你的链接数据库的密码设置错误