在Golang中获取数据库连接的连接字符串

时间:2018-08-21 15:55:14

标签: unit-testing go

我正在尝试测试此功能:

//OpenConnection opens a connection to a MySQL database by `connStr`
// or returns error. If `connStr` is empty, error is returned.
//
// Parameters:
// - `connStr`: the URL of the database to connect to
// - `interpolateParams` : should we interpolate parameters?
//
// Returns:
// - pointer to the database connection
// - any errors that happened during this process
func OpenConnection(connStr string, interpolateParams bool) (*sql.DB, *errors.ErrorSt) {
    if connStr == "" {
        return nil, errors.Database().ReplaceMessage("No database connection string.")
    }
    connStr = connStr + "?parseTime=true&multiStatements=true"
    if interpolateParams {
        connStr += "&interpolateParams=true"
    }

    db, err := sql.Open("mysql", connStr)
    if err != nil {
        return nil, errors.Database().AddDetails(err.Error(), connStr)
    }
    return db, nil
}
对于interpolateParams,为

。我正在筛选the official documentation,看不到从sql.DB获取连接字符串的简单方法。由于这是单元测试,因此,我当然要使用伪造的连接URL来实现该功能。

是否可以从sql.DB获取连接URL来检查插值查询字符串?

1 个答案:

答案 0 :(得分:0)

database/sql主要致力于成为使用SQL做事的接口。连接字符串通常是特定于驱动程序的,因此我将查看您使用的驱动程序以获取如何获取连接字符串的线索。在您的情况下,根据顶部的注释判断,您正在使用MySQL,因此我假设您会使用go-sql-driver/mysql。您可以将其直接导入代码中(而不是使用空白导入),并访问Config结构,在此处记录:https://stackoverflow.com/a/43042420/4381942,该结构从传递给sql.Open的dsn中填充>

相关问题