sqlx基础语法与应用
```
引用:
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
```
初始化
```
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
}
解释:
上面的var声明的是一个空的结构体的指针
在init方法中,通过Open方法来填充Db这个结构体的字段,之后等于var中的结构体的指针,赋值
```
操作
```
删除:
_, err := Db.Exec("delete from User where user_id=?", 1)
if err != nil {
log.Println("exec failed, ", err)
return
}
插入:
r, err := Db.Exec("insert into person(username)values(?)", "1",)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
查询:
err := Db.Select(&User, "select id, other from person where user_id=?", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
更新:
_, err := Db.Exec("update User set username=? where user_id=?", "username", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
```