【问题标题】:How to exec sql file with commands in golang如何在golang中使用命令执行sql文件
【发布时间】:2018-09-07 18:24:12
【问题描述】:

大家,我在 golang 中使用 postgresql 有一些问题。 我有一个 sql 文件(database.sql),在启动我的服务器之前我想执行一些命令,它看起来像这样

CREATE TABLE forums (
  id BIGSERIAL primary key,
  slug TEXT NOT NULL UNIQUE,
  title TEXT,
  author TEXT references users(login),
  threads BIGINT DEFAULT 0,
  posts BIGINT DEFAULT 0
);

我知道,我应该使用 db.Exec(request),但我有很多请求(“CREATE TABLE 用户”等...)

我不知道该怎么做

帮助,非常感谢!

【问题讨论】:

    标签: sql database postgresql go


    【解决方案1】:

    您可以将文件内容读入字符串并将其传递给Exec

    query, err := ioutil.ReadFile("path/to/database.sql")
    if err != nil {
        panic(err)
    }
    if _, err := db.Exec(query); err != nil {
        panic(err)
    }
    

    如果您的database.sql 以这种方式格式化,或者它包含破坏db.Exec 的查询,那么您可以将os/execpsql 一起使用(如果它安装在代码所在的机器上)运行)。

    cmd := exec.Command("psql", "-d", "database_name", "-f", "path/to/database.sql")
    stderr, err := cmd.StderrPipe()
    if err != nil {
        panic(err)
    }
    
    if err := cmd.Start(); err != nil {
        panic(err)
    }
    
    errout, _ := ioutil.ReadAll(stderr)
    if err := cmd.Wait(); err != nil {
        fmt.Println(errout)
        panic(err)
    }
    

    【讨论】:

    • 我可以用Exec执行各种'create table'?
    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 2021-03-13
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多