MySQL数据库5:Go与MySQL的交互

栏目: Go · 发布时间: 6年前

内容简介:版权声明:本文为博主尹成联系QQ77025077,微信18510341407原创文章,欢迎转载侵权不究。 https://blog.csdn.net/yincheng01/article/details/84134161

版权声明:本文为博主尹成联系QQ77025077,微信18510341407原创文章,欢迎转载侵权不究。 https://blog.csdn.net/yincheng01/article/details/84134161

下载第三方依赖

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

引入依赖

import (
	"github.com/jmoiron/sqlx"

	//执行mysql包的init方法
	_"github.com/go-sql-driver/mysql"

	"fmt"
)

建立测试数据库表

create database mydb charset=utf8;

use mydb;

create table person(
  id int primary key auto_increment,
  name varchar(20) unique not null,
  age int default 0,
  dollar float default 1
);

alter table person add sex bool;
alter table person add schoolday date;
alter table person add birthtime datetime;

定义与数据表向匹配的结构体

/*
id | name   | poem | age  | dollar  | sex  | schoolday  | birthtime
*/
type Person struct {
	//所有属性必须公开——框架会转化查询结果为结构体对象
	//标签名写法:`db:"表字段名"`
	Name string `db:"name"`
	Age int `db:"age"`
	Dollar float32 `db:"dollar"`
}

执行增删改查操作

  • 增删改的方式是db.Exec(sql)
  • 查询的方式是:db.select(&model,sql)
func main() {
	//连接数据库
	db, _ := sqlx.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/mydb")
	defer db.Close()

	//执行增删改,获得受影响的行数
	result, _ := db.Exec("insert into person(name,age,sex,schoolday,birthtime) values(?,?,?,?,?);", "双黄蛋", 35, false, 20080813, 20180814164300)
	rowsAffected, _:= result.RowsAffected()
	lastInsertId, _ := result.LastInsertId()
	fmt.Println("受影响的行数",rowsAffected,"最后一条记录的id",lastInsertId)

	//执行增删改
	db.Exec("insert into person(name,age,sex,schoolday,birthtime) values(?,?,?,?,?);", "双黄蛋", 35, false, 20080813, 20180814164300)
	db.Exec("delete from person where id=?;", 2)
	db.Exec("update person set name=? where name=?;", "张俩蛋","张全蛋")

	//执行查询,获得person对象
	//用于接收的数据类型是【结构体切片】,必须包含查询字段对应的公开属性,属性标签应写作:`db:"表字段名"`
	var ps []Person

	//第一个参数是【结构体切片】的地址
	err := db.Select(&ps, "select name,age,dollar from person where name like ?;", "%蛋")
	if err!=nil{
		fmt.Println("err=",err)
	}
	fmt.Printf("%T,%v\n", ps, ps)

	fmt.Println("执行成功!")
}

学院 Go 语言视频主页

https://edu.csdn.net/lecturer/1928

清华团队带你实战区块链开发

扫码获取海量视频及源码 QQ群:721929980

MySQL数据库5:Go与MySQL的交互

以上所述就是小编给大家介绍的《MySQL数据库5:Go与MySQL的交互》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hacker's Delight

Hacker's Delight

Henry S. Warren Jr. / Addison-Wesley / 2002-7-27 / USD 59.99

A collection useful programming advice the author has collected over the years; small algorithms that make the programmer's task easier. * At long last, proven short-cuts to mastering difficult aspec......一起来看看 《Hacker's Delight》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具