GolangでのMYSQLデータベースのバックアップ

9942 ワード

出典を明記してください.https://blog.csdn.net/qq_23179075/article/details/83306104

GolangでのMYSQLデータベースのバックアップ

package main

import (
	"common"
	"io/ioutil"
	"log"
	"os/exec"
	"time"
)

func main() {
	BackupMySqlDb("localhost", "3306", "root", "root", "dcim", "", "E:/")
}

/**
 *
 *  MySql 
 * @param 	host: 			 : localhost
 * @param 	port:			 : 3306
 * @param 	user:			 : root
 * @param 	password:		 : root
 * @param 	databaseName:	 : test
 * @param 	tableName:		 : user
 * @param 	sqlPath:		 SQL : D:/backup/test/
 * @return 	backupPath
 *
 */
func BackupMySqlDb(host, port, user, password, databaseName, tableName, sqlPath string) (error,string)  {
	var cmd *exec.Cmd

	if tableName == "" {
		cmd = exec.Command("mysqldump", "--opt", "-h"+host, "-P"+port, "-u"+user, "-p"+password, databaseName)
	} else {
		cmd = exec.Command("mysqldump", "--opt", "-h"+host, "-P"+port, "-u"+user, "-p"+password, databaseName, tableName)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
		return err,""
	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
		return err,""
	}

	bytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
		return err,""
	}
	now := time.Now().Format("20060102150405")
	var backupPath string
	if tableName == "" {
		backupPath = sqlPath+databaseName+"_"+now+".sql"
	} else {
		backupPath = sqlPath+databaseName+"_"+tableName+"_"+now+".sql"
	}
	err = ioutil.WriteFile(backupPath, bytes, 0644)

	if err != nil {
		panic(err)
		return err,""
	}
	return nil,backupPath
}


備考:MySqlbinディレクトリを環境変数のpath下に設定する必要があります.