英文:
Wrapped sql.DB by struct can't invoke methods in instance
问题
我的目标是使用一个结构体来封装sql.DB,以便做一些超出sql.DB功能的事情。
我创建的实例无法工作,并在运行时给出以下错误:
DbConn.db.prepare undefined (cannot refer to unexported field or method sql.(*DB)."".prepare)
我的代码如下:
type DatabaseConn struct {
driverName string
databaseName string
userName string
password string
dataSourceName string
db *sql.DB
}
func (d DatabaseConn) Open() error {
d.driverName = DB_DRNAME
d.userName = DB_UNAME
d.password = DB_PWD
d.databaseName = DB_DBNAME
d.dataSourceName = fmt.Sprintf("%s:%s@/%s?charset=utf8", d.userName, d.password, d.databaseName)
db, err := sql.Open(d.driverName, d.dataSourceName)
return err
}
func (d *DatabaseConn) Close() error {
defer func() {
if err := recover(); err != nil {
fmt.Println("Trying to handle error in DatabaseConn.Close(): ", err)
}
}()
err := d.db.Close()
return err
}
我试图创建一个实例并调用sql.DB的方法。
var dbConn DatabaseConn
dbConn.Open()
defer dbConn.Close()
dbQuery := fmt.Sprintf("SELECT * FROM ms_node WHERE node_id = ?")
getNodeRecord, err := dbConn.db.Prepare(dbQuery)
错误消息指向这里。
./server.go:343: dbConn.db.prepare undefined (cannot refer to unexported field or method sql.(*DB)."".prepare)
(个人背景:我是一个两周的新手)
英文:
My goal is using a struct to wrap sql.DB to do something more than sql.DB.
The instance I create can't work and give me this error when I run it.
DbConn.db.prepare undefined (cannot refer to unexported field or method sql.(*DB)."".prepare)
My code is:
type DatabaseConn struct {
driverName string
databaseName string
userName string
password string
dataSourceName string
db *sql.DB
}
func (d DatabaseConn)Open() error {
d.driverName = DB_DRNAME
d.userName = DB_UNAME
d.password = DB_PWD
d.databaseName = DB_DBNAME
d.dataSourceName = fmt.Sprintf("%s:%s@/%s?charset=utf8",d.userName, d.password, d.databaseName)
db, err := sql.Open(d.driverName, d.dataSourceName)
return err
}
func (d *DatabaseConn)Close() error {
defer func() {
if err := recover(); err != nil {
fmt.Println("Trying to handle error in DatabaseConn.Close(): ", err)
}
}()
err := d.db.Close()
return err
}
I am trying to create an instance and invoke sql.DB method.
var dbConn DatabaseConn
dbConn.Open()
defer dbConn.Close()
dbQuery := fmt.Sprintf("SELECT *, FROM ms_node WHERE node_id = ?")
getNodeRecord, err := dbConn.db.prepare(dbQuery)
The error message is pointed here.
./server.go:343: dbConn.db.prepare undefined (cannot refer to unexported field or method sql.(*DB)."".prepare)
(Personal background: I am newbie for 2 weeks)
答案1
得分: 1
Prepare
函数以大写字母开头
所以你应该这样写:
getNodeRecord, err := dbConn.db.Prepare(dbQuery)
英文:
The function Prepare
starts with a capital letter
So you should have:
getNodeRecord, err := dbConn.db.Prepare(dbQuery)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论