【英文】Go语言通过sqlx模块操作数据库

Introduction

Go language uses the sqlx module to operate on databases and optimize query operations.

Optimizing database connections

  • Use sqlx.Connect() function instead of sql.Open() function and sql.Ping() function.
1
db, err := sqlx.Connect("mysql", "<username>:<password>@tcp(<host>:<port>)/<database>")

Optimizing database query operations

Querying a single record

  • The query result will be automatically encapsulated into a struct.

<sql>: SQL query statement
<param>: parameter to be passed to the ? placeholder

1
2
3
4
5
6
7
8
9
type User struct {
Username string
Password string
}

func main {
var user User
db.Get(&user, <sql>, <param>)
}

Querying multiple records

1
2
3
4
5
6
7
8
9
type User struct {
Username string
Password string
}

func main {
var users []User
db.Select(users, <sql>, <param>)
}

Completion

References

Bilibili - Groundhog Documentation