7

【笔记】Go语言通过Sqlx模块操作Mysql数据库

 2 years ago
source link: https://loli.fj.cn/2023/03/27/Go%E8%AF%AD%E8%A8%80%E9%80%9A%E8%BF%87Sqlx%E6%A8%A1%E5%9D%97%E6%93%8D%E4%BD%9CMysql%E6%95%B0%E6%8D%AE%E5%BA%93/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【笔记】Go语言通过Sqlx模块操作Mysql数据库

Go语言通过Sqlx模块操作Mysql数据库提升查询效率

go get github.com/jmoiron/sqlx
import (
"github.com/jmoiron/sqlx"
_ "github.com/go-sql-driver/mysql"
)

连接数据库

<username>:用户名
<password>:密码
<host>:数据库地址
<port>:数据库端口
<database>:需要连接的数据库名

db, err := sqlx.Connect("mysql", "<username>:<password>@tcp(<host>:<port>)/<database>")
  • sqlx底层通过反射获取结构体的属性,来将结果集自动映射

用于映射数据表的结构体

type User struct {
Username string
Password string
}

查询单条数据

var user User
err := db.Get(&user, "SELECT * FROM user WHERE username=?", "user")

查询多条数据

var users []User
err := db.Get(&users, "SELECT * FROM user")
  • 其他的函数与原生sql模块相同

哔哩哔哩——地鼠文档


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK