douhan8892 2018-05-11 23:34
浏览 129
已采纳

Go数据库连接器:go-sql-driver可以工作,其他所有“未知的驱动程序,忘记了导入?”

When I try to use database/sql in this way it compiles and works:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

But if I try to use postgres specific connectors it doesn't even compile:

import(
    "database/sql"
    _ "github.com/lib/pq"
)

import(
    "database/sql"
    _ "github.com/jbarham/gopgsqldriver"
)

both fail with the error

sql: unknown driver "mysql" (forgotten import?)

I have done go get for both of these packages, and am really not sure why it is not compiling

  • 写回答

1条回答 默认 最新

  • dongying9712 2018-05-12 00:04
    关注

    Are you doing

    db, err := sql.Open("mysql",
    

    later on? When you import "github.com/lib/pq" for example, it registers itself by calling sql.Register, and then in the source of sql.Open you have:

    func Open(driverName, dataSourceName string) (*DB, error) {
        driversMu.RLock()
        driveri, ok := drivers[driverName]
        driversMu.RUnlock()
        if !ok {
            return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
        }
    }
    

    So, since you are no longer importing mysql, you need to change sql.Open to use the pq driver (or whichever one you end up picking).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?