三个文件:
db.go :
package config import ( "database/sql" "fmt" "log" "time" _ "github.com/go-sql-driver/mysql" ) const ( db_name = "text" db_host = "127.0.0.1" db_user = "root" db_pass = "root" db_port = 3306 ) var DB *sql.DB func Init() { dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) DB, err := sql.Open("mysql", dsn) if err != nil { fmt.Println("sql.Open error", err) return } //超时时间 DB.SetConnMaxLifetime(100 * time.Second) // 最大连接数 DB.SetMaxOpenConns(100) // 设置闲置的连接数 DB.SetMaxIdleConns(16) if err := DB.Ping(); err != nil { log.Fatal("DB.Ping = ", err) } }
work.go :
package config import "fmt" func GetOne() { var userid int _ = DB.QueryRow("select userid from s_work where itemid = 651054").Scan(&userid) fmt.Println("userid = ", userid) }
db_test.go :
package config import ( "testing" ) func TestInit(t *testing.T) { Init() GetOne() }
用db_test.go测试 运行: go test -v .\db_test.go .\db.go .\work.go
显示错误:
解决办法:
= 与 := 的区别
= 就是单纯的赋值
:= 具有声明变量的功能
改前 用的 := DB, err := sql.Open("mysql", dsn) 改后 用 = var err error DB, err = sql.Open("mysql", dsn)