0

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)

4
  • Is all of this code within the same package? You should also remove your use of defer - it doesn't help make your code clearer or safer. Commented Mar 16, 2016 at 1:13
  • @elithrar Yes. I guess they are in one package, as they are in one .go file. I guess something wrong with the pointer and the instance. But I can't tell there the problem is. Sorry, I didn't clean defer out. I do it right now. Commented Mar 16, 2016 at 1:48
  • I think you want sql.Open to assign to d.db, not just db. Also possible sql syntax error: *, Commented Mar 16, 2016 at 2:51
  • Sorry! I forgot paste these functions into question. I do it now. Commented Mar 16, 2016 at 3:08

1 Answer 1

1

The function Prepare starts with a capital letter ;)

So you should have:

getNodeRecord, err := dbConn.db.Prepare(dbQuery)
Sign up to request clarification or add additional context in comments.

1 Comment

I spent hours to find this bug! THANK YOU!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.