Last active
November 12, 2019 16:50
-
-
Save tangx/3b1ee7e3eb197cffa24cf4a3ab26632c to your computer and use it in GitHub Desktop.
init 初始化
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 全局变量 | |
var db *sql.DB | |
func init() { | |
NewConn(dsn) | |
} | |
// NewConn return a DB conn | |
func NewConn(dsn string) (err error) { | |
// sql.Open 不会 | |
db, err = sql.Open("mysql", dsn) | |
if err != nil { //检查 dsn 格式是否正确s | |
log.Println(err) | |
return err | |
} | |
err = db.Ping() // 检查数据库是否连接成功 | |
if err != nil { | |
log.Println(err) | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
init在引入的时候就被调用,因此,当执行
query
的时候,就没有再执行NewConn
创建连接。