Article Directory
We will learn to use Golang to connect to the MySQL database this time, and use Golang to implement the CRUD operation of the database.
Build environment
First we create a Golang project, and configure the project GOPATH, this step can refer to my blog Golang environment installation & IDEA development Golang .
Because we are using a MySQL database, we need to obtain Golang's MySQL database driver.
We execute the go get
command in the GOPATH directory of the project to obtain the MySQL driver. After the command is successfully executed, the MySQL driver package will be downloaded directly from the Internet to the GOPATH
directory under your src
directory.
go get -u github.com/go-sql-driver/mysql
After the Golang project environment is built, we also need to create a database table.
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
`password` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `nameindex` (`name`(10))
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Project structure
Write structure
In order to be able to easily encapsulate the data obtained from the database, we create a Golang structure to encapsulate our data.
We create a bean
package, and then create a user.go
file under the package .
user.go
package bean
type User struct {
id int
name string
password string
}
func (user *User) GetId() int {
return user.id
}
func (user *User) SetId(id int) {
user.id = id
}
func (user *User) GetName() string {
return user.name
}
func (user *User) SetName(name string) {
user.name = name
}
func (user *User) GetPassword() string {
return user.password
}
func (user *User) SetPassword(password string) {
user.password = password
}
Write a database connection tool
Because you need to get a database connection every time you connect to a database, we directly encapsulate the database connection operation as a method, so that you don't have to perform the step of getting a connection every time.
We create a util
package and create a initdb.go
file under the package .
initdb.go
package util
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"strings"
)
//我们先将数据库配置信息定义成为常量
const (
userName = "root"
password = "admin"
ip = "127.0.0.1"
port = "3306"
dbName = "db_database08"
)
//初始化数据库连接,返回数据库连接的指针引用
func InitDB() *sql.DB {
//Golang数据连接:"用户名:密码@tcp(IP:端口号)/数据库名?charset=utf8"
path := strings.Join([]string{userName, ":", password, "@tcp(", ip, ":", port, ")/", dbName, "?charset=utf8"}, "")
//打开数据库,前者是驱动名,所以要导入: _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", path)
if err != nil {
//如果打开数据库错误,直接panic
panic(err)
}
//设置数据库最大连接数
db.SetConnMaxLifetime(10)
//设置上数据库最大闲置连接数
db.SetMaxIdleConns(5)
//验证连接
if err := db.Ping(); err != nil {
panic(err)
}
//将数据库连接的指针引用返回
return db
}
CRUD operation
Insert operation
We create a insert
package, create a insert.go
file under the package
package main
import (
"fmt"
"mysql/util"
)
func main() {
//使用工具获取数据库连接
db := util.InitDB()
//开启事务
tx, err := db.Begin()
if err != nil {
//事务开启失败,直接panic
panic(err)
}
//准备SQL语句
sql := "insert into tb_user (`name`, `password`) values (?, ?)"
//对SQL语句进行预处理
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
result, err := stmt.Exec("阿部多瑞","123")
if err != nil {
//SQL执行失败,直接panic
panic(err)
}
//提交事务
tx.Commit()
//返回插入记录的id
fmt.Println(result.LastInsertId())
}
Select operation
We create a select
package, create a select.go
file under the package
package main
import (
"fmt"
"mysql/bean"
"mysql/util"
)
func main() {
//使用工具获取数据库连接
db := util.InitDB()
//准备SQL语句
sql := "select * from tb_user"
//对SQL语句进行预处理
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
rows, err := stmt.Query()
if err != nil {
//SQL执行失败,直接panic
panic(err)
}
var users []bean.User
for rows.Next() {
var id int
var name, password string
err := rows.Scan(&id, &name, &password)
if err != nil {
//读取结果集失败
panic(err)
}
var user bean.User
user.SetId(id)
user.SetName(name)
user.SetPassword(password)
users = append(users, user)
}
fmt.Println(users)
}
Update operation
We create a update
package, create a update.go
file under the package
package main
import (
"mysql/util"
)
func main() {
//使用工具获取数据库连接
db := util.InitDB()
//开启事务
tx, err := db.Begin()
if err != nil {
//事务开启失败,直接panic
panic(err)
}
//准备SQL语句
sql := "update tb_user set `password` = ? where `id` = ?"
//对SQL语句进行预处理
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
_, err = stmt.Exec("789", 1)
if err != nil {
//SQL执行失败,直接panic
panic(err)
}
//提交事务
tx.Commit()
}
Delete operation
We create a delete
package, create a delete.go
file under the package
package main
import (
"mysql/util"
)
func main() {
//使用工具获取数据库连接
db := util.InitDB()
//开启事务
tx, err := db.Begin()
if err != nil {
//事务开启失败,直接panic
panic(err)
}
//准备SQL语句
sql := "delete from tb_user where `id` = ?"
//对SQL语句进行预处理
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
_, err = stmt.Exec(1)
if err != nil {
//SQL执行失败,直接panic
panic(err)
}
//提交事务
tx.Commit()
}