sql导入工具自动化

Alex灬Liu · · 455 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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)
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:Alex灬Liu

查看原文:sql导入工具自动化

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

455 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传