ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 1. 安装sqlx ~~~go go get github.com/jmoiron/sqlx ~~~ ## 2. 基本使用 连接数据库 ~~~go var db *sqlx.DB func initDB() (err error) { dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True" db, err = sqlx.Connect("mysql", dsn) if err != nil { fmt.Printf("connect DB failed, err:%v\n", err) return } db.SetMaxOpenConns(20) db.SetMaxIdleConns(10) return } func main() { err := initDB() if err != nil { fmt.Printf("init db failed, err:%v\n", err) return } defer db.Close() fmt.Println("connected to db...") } ~~~ ## 3. 插入数据 ~~~ // 插入数据 func insertRowDemo() { sqlStr := "insert into user(name, age) values (?, ?)" result, err := db.Exec(sqlStr, "Cindy", 23) if err != nil { fmt.Printf("insert data failed, err:%v\n", err) return } lastID, err := result.LastInsertId() if err != nil { fmt.Printf("get last id failed, err:%v\n", err) return } fmt.Printf("insert successfully, last id is %d.\n", lastID) } ~~~ ### 4. NamedExec `DB.NamedExec`方法用来绑定SQL语句与结构体或map中的同名字段。 ~~~ func insertUserDemo() { sqlStr := "insert into user(name, age) values(:name, :age)" db.NamedExec(sqlStr, map[string]interface{}{ "name": "ddd", "age": 30, }) fmt.Printf("insert data successfully.") return } ~~~