首页 > 代码库 > MySql数据备份

MySql数据备份

MySql数据备份

1. cmd 环境下备份

cmd环境下备份mysql数据库可用到如下命令:

1、备份某表

mysqldump -u username -p dbname table1 table2 ...-> BackupName.sql

参数说明

dbname表示数据库的名称;

table1table2表示需要备份的表的名称,为空则整个数据库备份;

BackupName.sql表示备份文件的名称,文件名前面可以加上一个绝对路径。

2、备份多个数据库

mysqldump -u username -p --databases dbname2 dbname2 > BackupName.sql

3、备份所有数据库

mysqldump -u username -p -all-databases > BackupName.sql

4、数据还原

mysql -u root -p [dbname] < backup.sq

2. 调用mysqldump.exe备份

有时候在java代码中需要定时作业备份,实现自动备份。这时候可采用如下方式进行数据备份。大致流程是:

1、创建bat文件

2、调用bat文件,获取输入流写入备份文件中

代码示例如下:

 

package com.hymake.xmq;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Date;

/**
 * MySql数据备份工具类
 * @author xiongmq
 *
 */
public class MySqlBackup {
    
    public static void main(String[] args) {
        doBackup();
    }

    //mySql数据备份
    public static boolean doBackup(){
        boolean flag=false;
        //设置备份信息
        String databaseName="weixin";//数据库名字
        String mysqldumpUrl="C:\\Program Files\\MySQL\\MySQL Server 5.5";//mysql安装位置
        String savePath="d:\\数据备份"; //备份文件保存位置
        String host="127.0.0.1";//主机ip
        String port="3306";//端口
        String userName="root";//登录名
        String password="123456";//登录密码
        //初始化bat文件
        String dataBackupBatPath = System.getProperty("java.io.tmpdir")+ "\\dataBackup.bat";
        //创建bat文件,好做调用
        getBackupBat(dataBackupBatPath);
        //拼凑备份命令
        StringBuilder cmdStr=new StringBuilder();
        cmdStr.append(dataBackupBatPath);
        Calendar cal = Calendar.getInstance();
        Date now =new Date();
        cal.setTime(now);
        String year=String.valueOf(cal.get(Calendar.YEAR));
        String month=cal.get(Calendar.MONTH)+1<10?"0"+String.valueOf(cal.get(Calendar.MONTH)+1):String.valueOf(cal.get(Calendar.MONTH)+1);
        String date=cal.get(Calendar.DATE)<10?"0"+String.valueOf(cal.get(Calendar.DATE)):String.valueOf(cal.get(Calendar.DATE));
        String hour=cal.get(Calendar.HOUR_OF_DAY)<10?"0"+String.valueOf(cal.get(Calendar.HOUR_OF_DAY)):String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
        String minute=cal.get(Calendar.MINUTE)<10?"0"+String.valueOf(cal.get(Calendar.MINUTE)):String.valueOf(cal.get(Calendar.MINUTE));
        String sec=cal.get(Calendar.SECOND)<10?"0"+String.valueOf(cal.get(Calendar.SECOND)):String.valueOf(cal.get(Calendar.SECOND));
        String sqlFielName=databaseName+"_"+year+month+date+hour+minute+sec;
        String sqlFielPath=year+"\\"+month;
        cmdStr.append(" \""+savePath+"\"");
        cmdStr.append(" \""+sqlFielPath+"\"");
        //获取数据库位置
        cmdStr.append(" \""+mysqldumpUrl+"\"");
        cmdStr.append(" "+host);
        cmdStr.append(" "+port);
        cmdStr.append(" "+userName);
        cmdStr.append(" "+password);
        cmdStr.append(" "+databaseName);
        cmdStr.append(" "+sqlFielName);
        try {
            //执行命令
            Process p = Runtime.getRuntime().exec(cmdStr.toString());
            InputStream fis=p.getInputStream();
            InputStreamReader isr=new InputStreamReader(fis);
            BufferedReader br=new BufferedReader(isr);
            while((br.readLine())!=null) {
                flag=true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
     * 创建bat文件
     * @param tempPath
     */
    public static boolean getBackupBat(String tempPath){
        boolean flag=false;
        StringBuilder  content=new StringBuilder();
        content.append("SET BACK_DIR=%1");
        content.append("\r\n");
        content.append("md %BACK_DIR%\\%2"); 
        content.append("\r\n");
        content.append("SET BACK_PATH=%BACK_DIR%\\%2");
        content.append("\r\n");
        content.append("SET MYSQL_PATH=%3");
        content.append("\r\n");
        content.append("%MYSQL_PATH%\\bin\\mysqldump.exe --opt -h%4 -P%5 -u%6 -p%7 %8> %BACK_PATH%\\%9.sql ");
        content.append("\r\n");
        content.append("echo 数据备份完毕!"); 
        String directoryPath = tempPath.substring(0, tempPath.lastIndexOf("\\"));
        String fileName = tempPath.substring(tempPath.lastIndexOf("\\") + 1, tempPath.length());
        boolean checkDirectoryIsExist = new File(directoryPath).exists();
        if(!checkDirectoryIsExist){
            new File(directoryPath).mkdirs();
        }
        try{
          File file = new File(directoryPath + File.separator + fileName);
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
          bw.write(content.toString());
          flag = true;
          bw.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return flag;
    }
}

 

MySql数据备份