golang
上代码 可以按照数据库和sql文件 编译后可直接执行
import (
"fmt"
"os/exec"
"strings"
)
//command是执行的shell,注意如果出错,string(out)的报错内容更详细
func Exec_Shell(command string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", command)
out, err := cmd.Output()
if err != nil{
fmt.Println(err)
}
return string(out), err
}
//command是执行的shell,注意如果出错,string(out)的报错内容更详细
func Exec_Mysql(command string) (string, error) {
cmd := exec.Command( "/bin/bash", "-c", command)
out, err := cmd.Output()
if err != nil{
fmt.Println(err)
}
return string(out), err
}
func Database_Create(db_name string, info map[string]string) (string, error) {
sql := strings.Replace(`CREATE DATABASE {database} DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;`, "{database}", db_name, -1)
command := "/usr/local/mysql/bin/mysql -P {port} -h {address} -u{username} -p{password} -e\"" + sql + "\""
command = strings.Replace(command, "{username}", info["username"], 1) //username
command = strings.Replace(command, "{password}", info["password"], 1) //password
command = strings.Replace(command, "{address}", info["hostname"], 1) //address
command = strings.Replace(command, "{port}", info["port"], 1) //port
fmt.Println("sql command",command)
return Exec_Mysql(command)
}
//执行sql文件,source为sql文件路径
func Database_Import(db_name, source string, info map[string]string) (string, error) {
command := "/usr/local/mysql/bin/mysql -P {port} -h {address} -u{username} -p{password} {database} < {source}"
command = strings.Replace(command, "{username}", info["username"], 1) //username
command = strings.Replace(command, "{password}", info["password"], 1) //password
command = strings.Replace(command, "{database}", db_name, 1) //database
command = strings.Replace(command, "{address}", info["hostname"], 1) //address
command = strings.Replace(command, "{source}", source, 1) //sql
command = strings.Replace(command, "{port}", info["port"], 1) //port
return Exec_Mysql(command)
}
func main(){
db_name := "test_x"
info := map[string]string{
"username":"root",
"password":"root",
"hostname":"127.0.0.1",
"port":"3306",
}
source := "test_x.sql"
_, _ = Database_Create(db_name, info)
fmt.Println("创建成功")
result,_ :=Database_Import(db_name, source, info)
fmt.Println("导入成功")
fmt.Println("result:",result)
}
有疑问加站长微信联系(非本文作者)