在 GO 中重用数据库连接和“无效内存地址”错误

我是 GO 新手,似乎无法找到有关在全局中重用数据库连接的错误的任何信息。这是导致错误的代码的简化版本:


包主


import (

    _ "github.com/denisenkom/go-mssqldb"

    "database/sql"

)


var debug = flag.Bool("debug", false, "enable debugging")

var password = flag.String("password", "*****", "the database password")

var port *int = flag.Int("port", 1433, "the database port")

var server = flag.String("server", "localhost", "the database server")

var user = flag.String("user", "*****", "the database user")

var db *sql.DB


func main() {

    // Parse the incoming flags to set variables.

    flag.Parse()


    // Output the database variables if the debug flag is set.

    if *debug {

        fmt.Printf(" password:%s\n", *password)

        fmt.Printf(" port:%d\n", *port)

        fmt.Printf(" server:%s\n", *server)

        fmt.Printf(" user:%s\n", *user)

    }


    // Build out the connection string to the database, and then open the connection to the database.

    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d", *server, *user, *password, *port)

    if *debug { fmt.Printf(" connString:%s\n", connString) }

    db, err := sql.Open("mssql", connString)

    if err != nil { log.Fatal("Open connection failed:", err.Error()) }

    err = db.Ping()

    if err != nil {

        fmt.Println("Cannot connect: ", err.Error())

        return

    }


    // Close the connection when we're all done.

    defer db.Close()


    // Truncate the existing records in the ListHubFeed

    res, err := db.Exec( `

        TRUNCATE TABLE foo

    ` )

    _ = res


    if err != nil {

        fmt.Println( "TRUNCATE TABLE failed", err )

    }


    eligible := verifyEligibility( "foo" )


}


func verifyEligibility( email string ) ( success bool ) {


    //Run each check individually, and if any one fails, return false and stop processing additional checks


    // if the routing email is bad, then we can't create an account, so kick it out.

    if( !govalidator.IsEmail( email ) ){

        writeToLog( email )

        return false

    }


    return true;


}


繁花如伊
浏览 202回答 1
1回答

凤凰求蛊

你的问题是db指针nil在你的writeToLog()函数的上下文中。罪魁祸首是这一行:db, err := sql.Open("mssql", connString)在这里,您将短变量声明运算符 ( :=) 与赋值运算符 ( =)混淆了。此指令db使用db局部变量覆盖全局变量,只能在您的main函数中访问(这称为shadowing,也适用于包名称等)。因此,使用的db变量writeToLog永远不会被初始化,因此是nil pointer dereference错误的。要修复它,您只需要修复您的声明,使其成为做作:var err errordb, err = sql.Open("mssql", connString)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go