:=
,您刚刚存储创建的 * DB
$ b
此行:
db,err:= NewDB(dbinfo)
db err db db nil * DB
var err error
db,err = NewDB(dbinfo)
if err!= nil {
log.Fatal )
}
原始答案如下。
nil
您不必将其导出(这是以大写字母开头的)。请注意,您有多个文件,只要它们是同一个包的一部分,它们就可以访问在另一个包中定义的标识符。
init()
sql.Open() DB。 Ping()
例如:
var db * sql.DB
func init(){
var err error
db,err = sql.Open(yourdrivername, )
if err!= nil {
log.Fatal(err)
}
if err = db.Ping(); err!= nil {
log.Fatal(err)
}
}
I have the following file structure:
models/db.go
type DB struct {
*sql.DB
}
var db *DB
func init() {
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
DB_USER, DB_PASSWORD, DB_NAME)
db, err := NewDB(dbinfo)
checkErr(err)
rows, err := db.Query("SELECT * FROM profile")
checkErr(err)
fmt.Println(rows)
}
func NewDB(dataSourceName string) (*DB, error) {
db, err := sql.Open("postgres", dataSourceName)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
return &DB{db}, nil
}
models/db_util.go
func (p *Profile) InsertProfile() {
if db != nil {
_, err := db.Exec(...)
checkErr(err)
} else {
fmt.Println("DB object is NULL")
}
}
dbInsertProfileNULL ptr exceptiondbdb_utils.go
db
dbinit()
:=*DB
This line:
db, err := NewDB(dbinfo)
dberrdbdbnil*DB
var err error
db, err = NewDB(dbinfo)
if err != nil {
log.Fatal(err)
}
Original answer follows.
nil
You don't have to export it (that's what starting it with a capital letter does). Note that it doesn't matter that you have multiple files as long as they are part of the same package, they can access identifiers defined in one another.
init()
sql.Open()DB.Ping()
For example:
var db *sql.DB
func init() {
var err error
db, err = sql.Open("yourdrivername", "somesource")
if err != nil {
log.Fatal(err)
}
if err = db.Ping(); err != nil {
log.Fatal(err)
}
}
这篇关于Golang:如何在包中的文件使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!