由struct包装的sql.DB无法调用实例

时间:2016-03-16 00:02:52

标签: go

我的目标是使用struct来包装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)

(个人背景:我是新手2周)

1 个答案:

答案 0 :(得分:1)

函数Prepare以大写字母开头;)

所以你应该:

getNodeRecord, err := dbConn.db.Prepare(dbQuery)