赞
踩
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
var db *sql.DB
func main() {
//数据存在校验
rows, err := db.Query("SELECT uuid FROM account WHERE username=?", "1")
if err != nil {
log.Println("QUERY ERROR: ", err)
}
defer rows.Close()
var uuid string
for rows.Next() {
err := rows.Scan(&uuid)
if err != nil {
log.Fatal("SCAN ERROR: ", err)
}
log.Println("UUID: ", uuid)
}
err = rows.Err()
if err != nil {
log.Fatal("ROWS ERROR", err)
}
}
func init() {
//初始化数据库连接池
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/loginserver?charset=utf8&loc=Asia%2FShanghai")
if err != nil {
log.Fatalln("DB CONNECT: ", err)
}
db.SetMaxOpenConns(200)
db.SetMaxIdleConns(5)
err = db.Ping()
if err != nil {
log.Fatalln("DB PING: ", err)
}
}
编译通过,运行的时候爆出异常
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc=0x465ab0]
goroutine 1 [running]:
panic(0x661d60, 0xc082002080)
C:/Go/src/runtime/panic.go:481 +0x3f4
database/sql.(*DB).conn(0x0, 0x1, 0xc082002e80, 0x0, 0x0)
C:/Go/src/database/sql/sql.go:778 +0xad0
database/sql.(*DB).query(0x0, 0x6f37a0, 0x29, 0xc08205de50, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0)
C:/Go/src/database/sql/sql.go:1073 +0x4d
database/sql.(*DB).Query(0x0, 0x6f37a0, 0x29, 0xc08205de50, 0x1, 0x1, 0x10000c08205de10, 0x0, 0x0)
C:/Go/src/database/sql/sql.go:1061 +0xaa
main.main()
D:/Work/Project/golang/src/MySQLStudy/main.go:14 +0x1e1
调试的时候发现,程序到main方法中的时候db为nil,空的
在网上查问题的时候看到http://tonybai.com/2015/01/13/a-hole-about-variable-scope-in-golang/《一个有关Golang变量作用域的坑》 ,关于“:=”的问题, ":=" 使得init方法中的db的值没有作用到全局变量db中。
修改后正常
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
var db *sql.DB
func main() {
//数据存在校验
rows, err := db.Query("SELECT uuid FROM account WHERE username=?", "1")
if err != nil {
log.Println("QUERY ERROR: ", err)
}
defer rows.Close()
var uuid string
for rows.Next() {
err := rows.Scan(&uuid)
if err != nil {
log.Fatal("SCAN ERROR: ", err)
}
log.Println("UUID: ", uuid)
}
err = rows.Err()
if err != nil {
log.Fatal("ROWS ERROR", err)
}
}
func init() {
//初始化数据库连接池
db, _ = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/loginserver?charset=utf8&loc=Asia%2FShanghai")
db.SetMaxOpenConns(200)
db.SetMaxIdleConns(5)
err := db.Ping()
if err != nil {
log.Fatalln("DB PING: ", err)
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。