go 语言操作 mysql 数据库

       学习go语言的第3天,对于go语言菜鸟的我来说,必须得记录一下学习的过程,以便后续查阅,同时希望这篇文章能给同样是菜鸟的你带来帮助(所有操作都是在Ubuntu16.04操作系统)。

首先,安装mysql数据库,这个在上一篇文章有介绍过,这里就不再叙述。

其次,安装 go 语言的mysql驱动

go get"github.com/go-sql-driver/mysql"
go get"github.com/jmoiron/sqlx"

接下来就是使用go 对mysql的相关操作(连接、表的创建,数据的增删改查、表的删除等):

1、导入所需的包

package main

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

2、定义连接mysql的参数 及 数据表结构体

// 连接 mysql 参数变量
var (
	usename  string = "root"
	password string = "12345678"
	serverIp string = "127.0.0.1"
	port     int    = 3306
	dbname   string = "userclass"
)

// 测试数据表的结构体
type userinfo struct {
	id   int
	name string
	age  int
	sex  string
	tel  string
	addr string
}

3、连接mysql数据库接口

/******************************************************************
    功能:连接mysql数据库
    参数:
        uName:  登录数据库的用户名
        pwd:    密码
        ipAddr: 数据库服务器地址
        pt:     数据库服务器端口号
        dName/: 数据库名称
    返回值:
        数据库句柄

******************************************************************/

func connect_mysql(uName string, pwd string, ipAddr string, pt int, dName string) *sqlx.DB {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", uName, pwd, ipAddr, pt, dName)
	fmt.Printf("dsn: %s\n", dsn)
	Db, err := sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("mysql connect fail, datail is [%s]", err.Error())
	}
	return Db
}

2、创建数据表接口

/*****************************************************************
    功能:创建数据表
    参数:
        Db:      数据库句柄
        tName:   表的名称
        
    返回值:
        0     成功
        -1    失败
******************************************************************/
func table_create(Db *sqlx.DB, tName string) int {
	cmd := fmt.Sprintf("create table %s(id int(4) not null primary key auto_increment,name char(20) not null,age int(4) not null default '0',sex char(4) not null default '男',tel char(16),addr char(200))", tName)
	fmt.Printf("create cmd: %s\n\n", cmd)

	_, err := Db.Exec(cmd)
	if err != nil {
		fmt.Printf(" create %s err\n", tName)
		return -1
	}
	fmt.Printf("create %s table ok\n", tName)
	return 0
}

3、删除数据表接口

/*****************************************************************
    功能:删除数据表
    参数:
        Db:      数据库句柄
        tName:   表的名称
    返回值:
        0     成功
        -1    失败
****************************************************************/

func del_table(Db *sqlx.DB, tName string) int {
	cmd := fmt.Sprintf("drop table %s", tName)
	fmt.Printf("create cmd: %s\n\n", cmd)

	_, err := Db.Exec(cmd)
	if err != nil {
		fmt.Printf(" delete %s table err\n", tName)
		return -1
	}
	fmt.Printf("delete %s table ok\n", tName)
	return 0
}

4、新增数据接口

/*****************************************************************
    功能:向指定的数据表里面新增一条数据
    参数:
        Db:       数据库句柄
        uinfo:    数据成员结构体
        table:    表的名称
    返回值:
        0     成功
        -1    失败
****************************************************************/
func add_record(Db *sqlx.DB, uinfo *userinfo, table string) int {
	cmd := fmt.Sprintf("insert into %s value(%d,'%s',%d,'%s','%s','%s')", table, uinfo.id, uinfo.name, uinfo.age, uinfo.sex, uinfo.tel, uinfo.addr)
	fmt.Printf("add cmd: %s\n", cmd)

	_, err := Db.Exec(cmd)
	if err != nil {
		fmt.Printf("mysql insert fail, datail is [%s]\n", err.Error())
		return -1
	}
	fmt.Printf("mysql insert name: %s success\n", uinfo.name)
	return 0
}

5、删除数据接口

/*****************************************************************
    功能:从数据表里面删除指定name的数据
    参数:
        Db:       数据库句柄
        name:     指定删除 name 相同的数据
        table:    表的名称
    返回值:
        0     成功
        -1    失败
****************************************************************/
func del_record(Db *sqlx.DB, name string, table string) int {

	cmd := fmt.Sprintf("delete from %s where name = '%s'", table, name)
	fmt.Printf("del cmd: %s\n", cmd)

	_, err := Db.Exec(cmd)
	if err != nil {
		fmt.Printf("mysql delete name %s fail, datail is [%s]\n", name, err.Error())
		return -1
	}
	fmt.Printf("mysql delete name: %s success\n", name)
	return 0
}

6、修改表中某个记录中的某个字段值

/*****************************************************************
    功能:修改table表中,指定name的数据记录中的tel值
    参数:
        Db:       数据库句柄
        name:     指定修改 name 相同的记录中tel字段的值
        table:    表的名称
        newtel:   新的tel值
    返回值:
        0     成功
        -1    失败
****************************************************************/
func update_record(Db *sqlx.DB, name string, table string, newTel string) int {

	uinfo, ret := find_record(Db, name, table)
	if ret != 0 {
		fmt.Printf("not found name is  %s data\n", name)
		return -1
	}
	fmt.Printf("\n\nbefor update %s tel is %s\n\n", uinfo.name, uinfo.tel)

	cmd := fmt.Sprintf("update %s set tel = %s where name = '%s'", table, newTel, name)
	fmt.Printf("update cmd: %s\n", cmd)

	_, err := Db.Exec(cmd)
	if err != nil {
		fmt.Printf("update table %s fail, datail is [%s]\n", table, err.Error())
		return -1
	}

	uinfo, ret = find_record(Db, name, table)
	if ret != 0 {
		fmt.Printf("not found name is  %s data\n", name)
		return -1
	}

	fmt.Printf("after update %s tel is %s\n\n", uinfo.name, uinfo.tel)

	return 0
}

7、查找表中某个记录接口

/*****************************************************************
    功能:查找table表中,指定name的数据记录
    参数:
        Db:       数据库句柄
        name:     指定查找 name 相同的记录
        table:    表的名称

    返回值:
        0     成功,同时返回数据记录
        -1    失败,同时返回nil
****************************************************************/
func find_record(Db *sqlx.DB, name string, table string) (*userinfo, int) {

	cmd := fmt.Sprintf("select * from %s where name = '%s'", table, name)
	fmt.Printf("find cmd: %s\n", cmd)

	var uf userinfo
	err := Db.QueryRow(cmd).Scan(&uf.id, &uf.name, &uf.age, &uf.sex, &uf.tel, &uf.addr)
	if err != nil {
		fmt.Printf("mysql find name %s fail, datail is [%s]\n", name, err.Error())
		return nil, -1
	}

	return &uf, 0
}

8、获取表中所有的记录接口

/*****************************************************************
    功能:获取table表中的所有数据记录
    参数:
        Db:       数据库句柄
        table:    表的名称

    返回值:
        0     成功,同时返回数据记录列表
        -1    失败,同时返回nil
****************************************************************/
func get_record(Db *sqlx.DB, table string) ([]userinfo, int) {

	cmd := fmt.Sprintf("select * from %s", table)
	fmt.Printf("get record cmd: %s\n", cmd)

	rows, err := Db.Query(cmd)
	if err != nil {
		fmt.Printf("mysql select table %s fail, datail is [%s]\n", table, err.Error())
		return nil, -1
	}

	var uinfo []userinfo
	for rows.Next() {
		var uf userinfo
		err = rows.Scan(&uf.id, &uf.name, &uf.age, &uf.sex, &uf.tel, &uf.addr)
		if err != nil {
			fmt.Println("rows fail")
		}

		fmt.Printf("find result is name: %s id: %d age: %d addr: %s sex: %s tel: %s\n", uf.name, uf.id, uf.age, uf.addr, uf.sex, uf.tel)
		uinfo = append(uinfo, uf)
	}

	return uinfo, 0
}

9、测试主入口

func main() {

	var Db *sqlx.DB = connect_mysql(usename, password, serverIp, port, dbname)
	defer Db.Close()
	if Db == nil {
		fmt.Printf("connect err\n")
	}

	tablename := "students"
	ret := table_create(Db, tablename)
	if ret == -1 {
		fmt.Println("create table fail\n")
		return
	}

	var studt userinfo
	studt.id = 1
	studt.addr = "东1号店铺"
	studt.age = 22
	studt.name = "咪咪"
	studt.sex = "女"
	studt.tel = "12345678"
	ret = add_record(Db, &studt, tablename)
	if ret == -1 {
		fmt.Printf("add record err\n")
		return
	}

	studt.id = 2
	studt.addr = "东2号店铺"
	studt.age = 12
	studt.name = "张三"
	studt.sex = "男"
	studt.tel = "12345678"
	ret = add_record(Db, &studt, tablename)
	if ret == -1 {
		fmt.Printf("add record err\n")
		return
	}

	studt.id = 3
	studt.addr = "东3号店铺"
	studt.age = 25
	studt.name = "小小"
	studt.sex = "女"
	studt.tel = "58585"
	ret = add_record(Db, &studt, tablename)
	if ret == -1 {
		fmt.Printf("add record err\n")
		return
	}

	uinfo, ret := find_record(Db, "张三", tablename)
	if ret != 0 {
		fmt.Printf("not found name is  张三 data\n")
	}

	fmt.Printf("find result is name: %s id: %d age: %d addr: %s sex: %s tel: %s\n", uinfo.name, uinfo.id, uinfo.age, uinfo.addr, uinfo.sex, uinfo.tel)

	uinfos, ret := get_record(Db, tablename)
	fmt.Println(uinfos)

	ret = update_record(Db, "张三", tablename, "900054321")
	if ret == -1 {
		fmt.Printf("update err\n")
		return
	}

	ret = del_record(Db, "小小", tablename)
	if ret == -1 {
		fmt.Println("del record err")
	}
	fmt.Println("after delete\n")
	uinfos, ret = get_record(Db, tablename)
	if ret == -1 {
		fmt.Printf("get record err\n")
	}
	fmt.Println(uinfos)
	fmt.Println("\n")

	ret = del_table(Db, tablename)
	if ret == -1 {
		fmt.Printf("delete table fail \n")
	}
	fmt.Println("\n")
}

把上述接口写在mysql.go文件,并保存好,

在Ubuntu下使用go命令执行mysql.go结果如下:

ty@ty:~/work/go$ 
ty@ty:~/work/go$ 
ty@ty:~/work/go$ go run mysql.go 
dsn: root:12345678@tcp(127.0.0.1:3306)/userclass?charset=utf8
create cmd: create table students(id int(4) not null primary key auto_increment,name char(20) not null,age int(4) not null default '0',sex char(4) not null default '男',tel char(16),addr char(200))

create students table ok
add cmd: insert into students value(1,'咪咪',22,'女','12345678','东1号店铺')
mysql insert name: 咪咪 success
add cmd: insert into students value(3,'张三',12,'男','12345678','东2号店铺')
mysql insert name: 张三 success
add cmd: insert into students value(2,'小小',25,'女','58585','东3号店铺')
mysql insert name: 小小 success
find cmd: select * from students where name = '张三'
find result is name: 张三 id: 3 age: 12 addr: 东2号店铺 sex: 男 tel: 12345678
get record cmd: select * from students
find result is name: 咪咪 id: 1 age: 22 addr: 东1号店铺 sex: 女 tel: 12345678
find result is name: 小小 id: 2 age: 25 addr: 东3号店铺 sex: 女 tel: 58585
find result is name: 张三 id: 3 age: 12 addr: 东2号店铺 sex: 男 tel: 12345678
[{1 咪咪 22 女 12345678 东1号店铺} {2 小小 25 女 58585 东3号店铺} {3 张三 12 男 12345678 东2号店铺}]
find cmd: select * from students where name = '张三'


befor update 张三 tel is 12345678

update cmd: update students set tel = 900054321 where name = '张三'
find cmd: select * from students where name = '张三'
after update 张三 tel is 900054321

del cmd: delete from students where name = '小小'
mysql delete name: 小小 success
after delete

get record cmd: select * from students
find result is name: 咪咪 id: 1 age: 22 addr: 东1号店铺 sex: 女 tel: 12345678
find result is name: 张三 id: 3 age: 12 addr: 东2号店铺 sex: 男 tel: 900054321
[{1 咪咪 22 女 12345678 东1号店铺} {3 张三 12 男 900054321 东2号店铺}]


create cmd: drop table students

delete students table ok


ty@ty:~/work/go$ 

结束语:对go及mysq的知识掌握有限,以上都是一些最基本的操作,后续将会继续深入学习,争取能够使用go语言开发一个高可用、高并发、高性能的服务器;

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

y20082478

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值