5
【笔记】Go语言通过sqlx模块操作数据库
source link: https://loli.fj.cn/2023/04/03/Go%E8%AF%AD%E8%A8%80%E9%80%9A%E8%BF%87sqlx%E6%A8%A1%E5%9D%97%E6%93%8D%E4%BD%9C%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.
【笔记】Go语言通过sqlx模块操作数据库
2023-04-03Go语言学习指北
Go语言通过sqlx模块操作数据库,优化查询操作
优化连接数据库
- 通过
sqlx.Connect()
函数代替sql.Open()
函数和sql.Ping()
函数
db, err := sqlx.Connect("mysql", "<username>:<password>@tcp(<host>:<port>)/<database>")
优化数据库查询操作
查询单条数据
- 查询结果会自动封装为一个结构体
<sql>
:SQL查询语句<param>
:?
占位符要传递的参数
type User struct {
Username string
Password string
}
func main {
var user User
db.Get(&user, <sql>, <param>)
}
查询多条数据
type User struct {
Username string
Password string
}
func main {
var users []User
db.Select(users, <sql>, <param>)
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK