【问题标题】:How to connect with MySQL using a unix socket?如何使用 unix 套接字连接 MySQL?
【发布时间】:2021-08-24 06:57:50
【问题描述】:

我想使用 Unix 套接字连接连接到 MySQL。我不确定如何在连接字符串中传递变量。我在某处读到我也可以使用 Config.FormatDSN 结构来定义值,但我不确定如何。

// Creates a database connection and returns its instance
func Connection() (*sql.DB, error) {
    conn, err := sql.Open("mysql", "username/password@unix(socketpath)/dbname")
    return conn, err
}

【问题讨论】:

    标签: mysql go


    【解决方案1】:

    所以,经过一些尝试和尝试,我找到了解决问题的方法。如果你想使用 Unix 套接字连接在 Golang 中连接 MySQL,你可以通过以下方式准备你的连接字符串

    {{username}}:{{password}}@unix({{socketPath}})/{{dbname}}?charset=utf8
    

    {{}} 中的值是变量。

    注意:套接字路径必须是绝对的。例如: /usr/local/bin/path/to/socket

    我发现此参考资料很有帮助 https://chromium.googlesource.com/external/github.com/go-sql-driver/mysql/+/a48f79b55b5a2107793c84c3bbd445138dc7f0d5/README.md

    如果您有兴趣,这里是完整的实现

    
    import (
        "database/sql"
        "fmt"
    
        _ "github.com/go-sql-driver/mysql"
    )
    
    type ConnectionSpecs struct {
        username   string
        password   string
        socketPath string
        database   string
    }
    
    func GetConnStr() string {
        connConfig := ConnectionSpecs{
            username:   "root",
            password:   "my-password",
            socketPath: "/usr/local/bin/path/to/socket",
            database:   "test",
        }
    
        connStr := connConfig.username + ":" + connConfig.password +
            "@unix(" + connConfig.socketPath + ")" +
            "/" + connConfig.database +
            "?charset=utf8"
        return connStr
    }
    
    // Creates a database connection and returns the same
    func Connection() (*sql.DB, error) {
        var connStr = GetConnStr()
        fmt.Println(connStr)
        conn, err := sql.Open("mysql", GetConnStr())
        return conn, err
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2019-02-12
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多