1.下载安装go操作mysql的驱动包
1.1下载安装当下比较流行的Go-SQL-Driver/MySQL
- 下载:
go get github.com/Go-SQL-Driver/MySQL
- 安装:
go install github.com/Go-SQL-Driver/MySQL
1.2导入mysql驱动包
import (
"database/sql"
_"github.com/Go-SQL-Driver/MySQL"
)
这下准备工作就完成了!
2.操作数据库
2.1连接数据库
Open函数:db, err := sql.Open("mysql", "用户名:密码@tcp(IP:端口)/数据库?charset=utf8")
例如:db, err := sql.Open("mysql","root:111111@tcp(127.0.0.1:3306)/userinfo?charset=utf8")
2.2创建表
CREATE TABLE `posts` (
`id` int(20) UNSIGNED NOT NULL AUTO_INCREMENT ,
`content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`id`),
UNIQUE INDEX `id` (`id`) USING BTREE
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=4
ROW_FORMAT=COMPACT
;
查看创建好的表结构
2.3事务
//在操作数据库之前执行,
db.Begin()
//例:
tx, err := db.Begin()
//保存到数据库: (有对数据库进行改动的时候必须要提交)
err := tx.Commit()
//回滚:
err := tx.Rollback()
//注意设置事务以后操作数据库就不是db了,而是 tx
2.4增加一条记录
- 直接使用Exec函数添加
res, err := tx.Exec("insert into posts (content, author) values (?, ?)", "我是一行文本","machooo")
- 首先使用Prepare获得stmt,然后调用Exec添加
stmt, err := tx.Prepare("insert into posts (content, author) values (?, ?)")
res, err := stmt.Exec("我是一行文本","machooo")
- 另一个经常用到的功能,获得刚刚添加数据的自增ID
id, err := res.LastInsertId()
代码截图
2.5删除一条记录
- 删除和上面的增加语法一样,只是把其中的INSERT语句改为DELETE语句
2.6获取一条记录
- 直接使用QueryRow()函数获取(这里直接写入了post结构体中)
err = tx.QueryRow("select id, content, author from posts where id = ?", id).Scan(&post.Id, &post.Content,&post.Author)
代码截图
2.7查询多条记录,并遍历
- Query 获取数据,for xxx.Next() 遍历数据
代码截图
2.8修改一条记录
- 修改和上面的增加语法一样,只是把其中的INSERT语句改为UPDATE语句
本文部分相关代码
package main
import (
"fmt"
"database/sql"
_ "github.com/Go-SQL-Driver/MySQL"
)
var Db *sql.DB
// connect to the Db
func init() {
var err error
//Open函数的真正作用是设置好链接数据库所需的各个结构,并以惰性的方式,等真正需要时才建立相应的链接。
Db, err = sql.Open("mysql", "root:111111@tcp(127.0.0.1:3306)/userinfo?charset=utf8")
if err != nil {
panic(err)
}
}
// Get a single post
func retrieve(id int) (post Post, err error) {
post = Post{}
tx, _ := Db.Begin()
err = tx.QueryRow("select id, content, author from posts where id = ?", id).Scan(&post.Id, &post.Content, &post.Author)
return
}
func getall() (err error) {
tx, _ := Db.Begin()
rows, err := tx.Query("select id, content, author from posts")
var id int
var content, author string
for rows.Next() {
if err := rows.Scan(&id, &content, &author); err != nil {
fmt.Println(err)
}
fmt.Println(id)
fmt.Println(content)
fmt.Println(author)
}
return
}
// Create a new post
func (post *Post) create() (err error) {
tx, err := Db.Begin()
statement := "insert into posts (content, author) values (?, ?) "
stmt, err := tx.Prepare(statement)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(post.Content, post.Author)
tx.Commit()
return
}
// Update a post
func (post *Post) update() (err error) {
tx, _ := Db.Begin()
_, err = tx.Exec("update posts set content = ?, author = ? where id = ?", post.Content, post.Author, post.Id)
tx.Commit()
return
}
// Delete a post
func (post *Post) delete() (err error) {
tx, _ := Db.Begin()
_, err = tx.Exec("delete from posts where id = ?", post.Id)
tx.Commit()
return
}