In the process of learning to use golang operation of the database, the database query the database using sqlx encountered error message
Source as follows:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
var DB *sqlx.DB
func initDb() error {
var err error
dsn := "root:123456@tcp(127.0.0.1:3306)/golang"
DB, err = sqlx.Open("mysql", dsn)
if err != nil {
return err
}
DB.SetMaxOpenConns(100)
DB.SetMaxIdleConns(16)
return nil
}
type User struct {
Id int64 `db:id`
Name sql.NullString `db:name`
Age int `db:age`
}
func testSqlxQuery() {
sqlstr := "select id,name,age from user where id=?"
var user User
err := DB.Get(&user, sqlstr, 3)
if err != nil {
fmt.Printf("select failed, err:%v\n", err)
return
}
fmt.Printf("user:%#v\n", user)
}
func main() {
err := initDb()
if err != nil {
fmt.Printf("init db failed, err:%v\n", err)
return
}
testSqlxQuery()
}
After go build, execute error:
missing destination name id in *main.User
Using sql database query the database no problem, but the use of sqlx error, by comparison found that the object is a definition of the structure, tag tag does not lead to double quotes, quotes after the problem is solved.
type User struct {
Id int64 `db:"id"`
Name sql.NullString `db:"name"`
Age int `db:"age"`
}
For such problems should pay special attention in the use of tag use Remember increase in double quotes, to avoid such low-level errors.