加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

go语言之行--golang操作redis、mysql大全

发布时间:2020-12-16 19:34:58 所属栏目:大数据 来源:https://redis.io/源码部署yum i
导读:一、redis 简介 redis(REmote DIctionary Server)是一个由Salvatore Sanfilippo写key-value存储系统,它由C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value类型的数据库,并提供多种语言的API。和Memcached类似,它支持存储的val

一、redis

简介

redis(REmote DIctionary Server)是一个由Salvatore Sanfilippo写key-value存储系统,它由C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value类型的数据库,并提供多种语言的API。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步,redis在3.0版本推出集群模式。

官方网站:https://redis.io/

源码部署

yum install gcc -y wget http://download.redis.io/redis-stable.tar.gz tar zxvf redis-stable.tar.gz cd redis-=/opt/app/redis install /etc/redis cp redis.conf /etc/redis/6379.conf cp utils/redis_init_script /etc/init.d/redis chmod a+x /etc/init.d/redis /etc/redis/6379bind 0.0.0.0 <span style="color: #008000;">#<span style="color: #008000;">监听地址
maxmemory 4294967296 <span style="color: #008000;">#
<span style="color: #008000;">限制最大内存(4G):

daemonize yes <span style="color: #008000;">#
<span style="color: #008000;">后台运行

<span style="color: #008000;">#<span style="color: #008000;">###启动与停止
/etc/init.d/<span style="color: #000000;">redis start
/etc/init.d/redis stop

查看版本信息

redis- 127.0.0.1:6379> redis_version:4.0.10000000002.6.32-64264

二、golang操作redis

安装

golang操作redis的客户端包有多个比如redigo、go-redis,github上Star最多的莫属redigo。

github地址:https://github.com/garyburd/redigo? 目前已经迁移到:https://github.com/gomodule/redigo?

文档:https://godoc.org/github.com/garyburd/redigo/redis

go get github.com/garyburd/redigo/

连接

Conn接口是与Redis协作的主要接口,可以使用Dial,DialWithTimeout或者NewConn函数来创建连接,当任务完成时,应用程序必须调用Close函数来完成操作。

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err := redis.Dial(<span style="color: #800000;">"<span style="color: #800000;">tcp<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">10.1.210.69:6379<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">connect redis error :<span style="color: #800000;">"<span style="color: #000000;">,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
defer conn.Close()
}

命令操作

通过使用Conn接口中的do方法执行redis命令,redis命令大全参考:http://doc.redisfans.com/

go中发送与响应对应类型:

"1",false -> "0"
可以使用GO的类型断言或者reply辅助函数将返回的interface{}转换为对应类型。

操作示例:

get、set

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
defer conn.Close()
_,err = conn.Do(<span style="color: #800000;">"<span style="color: #800000;">SET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">name<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">wd<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">redis set error:<span style="color: #800000;">"<span style="color: #000000;">,err)
}
name,err := redis.String(conn.Do(<span style="color: #800000;">"<span style="color: #800000;">GET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">name<span style="color: #800000;">"<span style="color: #000000;">))
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">redis get error:<span style="color: #800000;">"<span style="color: #000000;">,err)
} <span style="color: #0000ff;">else<span style="color: #000000;"> {
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">Got name: %s n<span style="color: #800000;">"<span style="color: #000000;">,name)
}
}

设置key过期时间

_,err = conn.Do(,) err !=

批量获取mget、批量设置mset

_,err = conn.Do(,,, err !== redis.Strings(conn.Do(, err !==

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">reflect<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err = conn.Do(<span style="color: #800000;">"<span style="color: #800000;">LPUSH<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">list1<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">ele1<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">ele2<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">ele3<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">redis mset error:<span style="color: #800000;">"<span style="color: #000000;">,err := redis.String(conn.Do(<span style="color: #800000;">"<span style="color: #800000;">LPOP<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">list1<span style="color: #800000;">"<span style="color: #000000;">))
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">redis POP error:<span style="color: #800000;">"<span style="color: #000000;">,res_type)
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">res : %s n<span style="color: #800000;">"<span style="color: #000000;">,res)
}
}
<span style="color: #008000;">//<span style="color: #008000;">res type : string
<span style="color: #008000;">//<span style="color: #008000;">res : ele3

hash操作

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">reflect<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err = conn.Do(<span style="color: #800000;">"<span style="color: #800000;">HSET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">student<span style="color: #800000;">",err := redis.Int64(conn.Do(<span style="color: #800000;">"<span style="color: #800000;">HGET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">age<span style="color: #800000;">"<span style="color: #000000;">))
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">redis HGET error:<span style="color: #800000;">"<span style="color: #000000;">,res_type)
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">res : %d n<span style="color: #800000;">"<span style="color: #000000;">,res)
}
}
<span style="color: #008000;">//<span style="color: #008000;">res type : int64
<span style="color: #008000;">//<span style="color: #008000;">res : 22

管道操作可以理解为并发操作,并通过Send(),Flush(),Receive()三个方法实现。客户端可以使用send()方法一次性向服务器发送一个或多个命令,命令发送完毕时,使用flush()方法将缓冲区的命令输入一次性发送到服务器,客户端再使用Receive()方法依次按照先进先出的顺序读取所有命令操作结果。

Send(commandName ,args ...{},err error)
  • Send:发送命令至缓冲区
  • Flush:清空缓冲区,将命令一次性发送至服务器
  • Recevie:依次读取服务器响应结果,当读取的命令未响应时,该操作会阻塞。

示例:

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
defer conn.Close()
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">HSET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">22<span style="color: #800000;">"<span style="color: #000000;">)
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">HSET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">Score<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">100<span style="color: #800000;">"<span style="color: #000000;">)
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">HGET<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">age<span style="color: #800000;">"<span style="color: #000000;">)
conn.Flush()

res1,err :</span>=<span style="color: #000000;"&gt; conn.Receive()
fmt.Printf(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;Receive res1:%v n</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res1)
res2,err :</span>=<span style="color: #000000;"&gt; conn.Receive()
fmt.Printf(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;Receive res2:%vn</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res2)
res3,err :</span>=<span style="color: #000000;"&gt; conn.Receive()
fmt.Printf(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;Receive res3:%sn</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res3)

}
<span style="color: #008000;">//<span style="color: #008000;">Receive res1:0
<span style="color: #008000;">//<span style="color: #008000;">Receive res2:0
<span style="color: #008000;">//<span style="color: #008000;">Receive res3:22

发布/订阅

redis本身具有发布订阅的功能,其发布订阅功能通过命令SUBSCRIBE(订阅)/PUBLISH(发布)实现,并且发布订阅模式可以是多对多模式还可支持正则表达式,发布者可以向一个或多个频道发送消息,订阅者可订阅一个或者多个频道接受消息。

示意图:

发布者:

订阅者:

操作示例,示例中将使用两个goroutine分别担任发布者和订阅者角色进行演示:

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">time<span style="color: #800000;">"<span style="color: #000000;">
)

func Subs() { <span style="color: #008000;">//<span style="color: #008000;">订阅者
conn,err := redis.Dial(<span style="color: #800000;">"<span style="color: #800000;">tcp<span style="color: #800000;">",err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
defer conn.Close()
psc :=<span style="color: #000000;"> redis.PubSubConn{conn}
psc.Subscribe(<span style="color: #800000;">"<span style="color: #800000;">channel1<span style="color: #800000;">") <span style="color: #008000;">//<span style="color: #008000;">订阅channel1频道
<span style="color: #0000ff;">for<span style="color: #000000;"> {
<span style="color: #0000ff;">switch v :=<span style="color: #000000;"> psc.Receive().(type) {
<span style="color: #0000ff;">case<span style="color: #000000;"> redis.Message:
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">%s: message: %sn<span style="color: #800000;">"<span style="color: #000000;">,v.Channel,v.Data)
<span style="color: #0000ff;">case<span style="color: #000000;"> redis.Subscription:
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">%s: %s %dn<span style="color: #800000;">"<span style="color: #000000;">,v.Kind,v.Count)
<span style="color: #0000ff;">case<span style="color: #000000;"> error:
fmt.Println(v)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
}
}

func Push(message <span style="color: #0000ff;">string) { <span style="color: #008000;">//<span style="color: #008000;">发布者
conn, := redis.Dial(<span style="color: #800000;">"<span style="color: #800000;">tcp<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">10.1.210.69:6379<span style="color: #800000;">"<span style="color: #000000;">)
,err1 := conn.Do(<span style="color: #800000;">"<span style="color: #800000;">PUBLISH<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">channel1<span style="color: #800000;">"<span style="color: #000000;">,message)
<span style="color: #0000ff;">if err1 !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">pub err: <span style="color: #800000;">"<span style="color: #000000;">,err1)
<span style="color: #0000ff;">return<span style="color: #000000;">
}

}

func main() {
go Subs()
go Push(<span style="color: #800000;">"<span style="color: #800000;">this is wd<span style="color: #800000;">"<span style="color: #000000;">)
time.Sleep(time.Second*<span style="color: #800080;">3<span style="color: #000000;">)
}
<span style="color: #008000;">//<span style="color: #008000;">channel1: subscribe 1
<span style="color: #008000;">//<span style="color: #008000;">channel1: message: this is wd

事务操作

MULTI,EXEC,DISCARD和WATCH是构成Redis事务的基础,当然我们使用go语言对redis进行事务操作的时候本质也是使用这些命令。

MULTI:开启事务

EXEC:执行事务

DISCARD:取消事务

WATCH:监视事务中的键变化,一旦有改变则取消事务。

示例:

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

func main() {
conn,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
defer conn.Close()
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">MULTI<span style="color: #800000;">"<span style="color: #000000;">)
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">INCR<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">foo<span style="color: #800000;">"<span style="color: #000000;">)
conn.Send(<span style="color: #800000;">"<span style="color: #800000;">INCR<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">bar<span style="color: #800000;">"<span style="color: #000000;">)
r,err := conn.Do(<span style="color: #800000;">"<span style="color: #800000;">EXEC<span style="color: #800000;">"<span style="color: #000000;">)
fmt.Println(r)
}
<span style="color: #008000;">//<span style="color: #008000;">[1,1]

redis连接池是通过pool结构体实现,以下是源码定义,相关参数说明已经备注:

type Pool </span></span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; TestOnBorrow is an optional application supplied function for checking </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; the health of an idle connection before the connection is used again by </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; the application. Argument t is the time that the connection was returned </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; to the pool. If the function returns an error,then the connection is </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; closed.</span>

<span style="color: #000000;"> TestOnBorrow func(c Conn,t time.Time) error

</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Maximum number of idle connections in the pool.</span>
MaxIdle <span style="color: #0000ff;"&gt;int  <span style="color: #ff6600;"&gt;//最大的空闲连接数,即使没有redis连接时依然可以保持N个空闲的连接,而不被清除,随时处于待命状态</span></span>

<span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Maximum number of connections allocated by the pool at a given time.
</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; When zero,there is no limit on the number of connections in the pool.</span>
MaxActive <span style="color: #0000ff;"&gt;int <span style="color: #ff6600;"&gt;//最大的激活连接数,同时最多有N个连接</span></span>

<span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Close connections after remaining idle for this duration. If the value
</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; is zero,then idle connections are not closed. Applications should set
</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; the timeout to a value less than the server's timeout.</span>

<span style="color: #000000;"> IdleTimeout time.Duration <span style="color: #ff6600;">//空闲连接等待时间,超过此时间后,空闲连接将被关闭

</span></span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; If Wait is true and the pool is at the MaxActive limit,then Get() waits
</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; for a connection to be returned to the pool before returning.</span>
Wait <span style="color: #0000ff;"&gt;bool  <span style="color: #ff6600;"&gt;//当配置项为true并且MaxActive参数有限制时候,使用Get方法等待一个连接返回给连接池</span></span>

<span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Close connections older than this duration. If the value is zero,then
</span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; the pool does not close connections based on age.</span>

<span style="color: #000000;"> MaxConnLifetime time.Duration
<span style="color: #008000;">//<span style="color: #008000;"> contains filtered or unexported fields
}

?示例:

import (
<span style="color: #800000;">"<span style="color: #800000;">github.com/garyburd/redigo/redis<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var<span style="color: #000000;"> Pool redis.Pool
func init() { <span style="color: #008000;">//<span style="color: #008000;">init 用于初始化一些参数,先于main执行
Pool =<span style="color: #000000;"> redis.Pool{
MaxIdle: <span style="color: #800080;">16<span style="color: #000000;">,MaxActive: <span style="color: #800080;">32<span style="color: #000000;">,IdleTimeout: <span style="color: #800080;">120<span style="color: #000000;">,Dial: func() (redis.Conn,error) {
<span style="color: #0000ff;">return redis.Dial(<span style="color: #800000;">"<span style="color: #800000;">tcp<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">10.1.210.69:6379<span style="color: #800000;">"<span style="color: #000000;">)
},}
}

func main() {

conn :</span>=<span style="color: #000000;"&gt;Pool.Get()
res,err :</span>= conn.Do(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;HSET</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;jack</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
fmt.Println(res,err)
res1,err :</span>= redis.String(conn.Do(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;HGET</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;name</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;))
fmt.Printf(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;res:%s,error:%v</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res1,err)

}
<span style="color: #008000;">//<span style="color: #008000;">0
<span style="color: #008000;">//<span style="color: #008000;">res:jack,error:

三、golang操作mysql

mysql目前来说是使用最为流行的关系型数据库,golang操作mysql使用最多的包go-sql-driver/mysql。

sqlx包是作为database/sql包的一个额外扩展包,在原有的database/sql加了很多扩展,如直接将查询的数据转为结构体,大大简化了代码书写,当然database/sql包中的方法同样起作用。

github地址:

  • https://github.com/go-sql-driver/mysql
  • https://github.com/jmoiron/sqlx

golang sql使用:

  • ?

安装

go

连接数据库

Db *= sqlx.Open(,= db

处理类型(Handle Types)

sqlx设计和database/sql使用方法是一样的。包含有4中主要的handle types:?

  • sqlx.DB - 和sql.DB相似,表示数据库。?
  • sqlx.Tx - 和sql.Tx相似,表示事物。?
  • sqlx.Stmt - 和sql.Stmt相似,表示prepared statement。?
  • sqlx.NamedStmt - 表示prepared statement(支持named parameters)

所有的handler types都提供了对database/sql的兼容,意味着当你调用sqlx.DB.Query时,可以直接替换为sql.DB.Query.这就使得sqlx可以很容易的加入到已有的数据库项目中。

此外,sqlx还有两个cursor类型:?

  • sqlx.Rows - 和sql.Rows类似,Queryx返回。?
  • sqlx.Row - 和sql.Row类似,QueryRowx返回。

相比database/sql方法还多了新语法,也就是实现将获取的数据直接转换结构体实现。

  • Get(dest interface{},…) error
  • Select(dest interface{},…) error?

<h3 id="exec">建表

以下所有示例均已以下表结构作为操作基础。

=InnoDB DEFAULT CHARSET=utf8

Exec使用

Exec和MustExec从连接池中获取一个连接然后只想对应的query操作。对于不支持ad-hoc query execution的驱动,在操作执行的背后会创建一个prepared statement。在结果返回前这个connection会返回到连接池中。

需要注意的是不同的数据库类型使用的占位符不同,mysql采用?作为占位符号。

  • MySQL 使用??
  • PostgreSQL 使用1,2等等?

Exec增删该示例

查询语法使用Query后续会提到

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

func init() {
db,<span style="color: #800000;">"<span style="color: #800000;">stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">open mysql failed,<span style="color: #800000;">"<span style="color: #000000;">,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
}

func main() {
result,err := Db.Exec(<span style="color: #800000;">"<span style="color: #800000;">INSERT INTO userinfo (username,password,department,email) VALUES (?,?,?)<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">123<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">it<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">wd@163.com<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">insert failed,error: <span style="color: #800000;">"<span style="color: #000000;">,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
id, :=<span style="color: #000000;"> result.LastInsertId()
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">insert id is :<span style="color: #800000;">"<span style="color: #000000;">,id)
,err1 := Db.Exec(<span style="color: #800000;">"<span style="color: #800000;">update userinfo set username = ? where uid = ?<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">jack<span style="color: #800000;">",<span style="color: #800080;">1<span style="color: #000000;">)
<span style="color: #0000ff;">if err1 !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">update failed error:<span style="color: #800000;">"<span style="color: #000000;">,err1)
} <span style="color: #0000ff;">else<span style="color: #000000;"> {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">update success!<span style="color: #800000;">"<span style="color: #000000;">)
}
_,err2 := Db.Exec(<span style="color: #800000;">"<span style="color: #800000;">delete from userinfo where uid = ? <span style="color: #800000;">",<span style="color: #800080;">1<span style="color: #000000;">)
<span style="color: #0000ff;">if err2 !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">delete error:<span style="color: #800000;">"<span style="color: #000000;">,err2)
}<span style="color: #0000ff;">else<span style="color: #000000;">{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">delete success<span style="color: #800000;">"<span style="color: #000000;">)
}

}
<span style="color: #008000;">//<span style="color: #008000;">insert id is : 1
<span style="color: #008000;">//<span style="color: #008000;">update success!
<span style="color: #008000;">//<span style="color: #008000;">delete success

sql预声明(Prepared Statements)

对于大部分的数据库来说,当一个query执行的时候,在sql语句数据库内部声明已经声明过了,其声明是在数据库中,我们可以提前进行声明,以便在其他地方重用。

stmt,err := db.Prepare(`SELECT * FROM place WHERE telcode=?= stmt.QueryRow(tx,err :=<span style="color: #000000;"> db.Begin()
txStmt,err :
= tx.Prepare(SELECT * FROM place WHERE telcode=?<span style="color: #000000;"&gt;)
row
= txStmt.QueryRow(<span style="color: #800080;">852)

当然sqlx还提供了Preparex()进行扩展,可直接用于结构体转换

stmt,err := db.Preparex(`SELECT * FROM place WHERE telcode=?= stmt.Get(&p,)

Query是database/sql中执行查询主要使用的方法,该方法返回row结果。Query返回一个sql.Rows对象和一个error对象。

在使用的时候应该吧Rows当成一个游标而不是一系列的结果。尽管数据库驱动缓存的方法不一样,通过Next()迭代每次获取一列结果,对于查询结果非常巨大的情况下,可以有效的限制内存的使用,Scan()利用reflect把sql每一列结果映射到go语言的数据类型如string,[]byte等。如果你没有遍历完全部的rows结果,一定要记得在把connection返回到连接池之前调用rows.Close()。

Query返回的error有可能是在server准备查询的时候发生的,也有可能是在执行查询语句的时候发生的。例如可能从连接池中获取一个坏的连级(尽管数据库会尝试10次去发现或创建一个工作连接)。一般来说,错误主要由错误的sql语句,错误的类似匹配,错误的域名或表名等。

在大部分情况下,Rows.Scan()会把从驱动获取的数据进行拷贝,无论驱动如何使用缓存。特殊类型sql.RawBytes可以用来从驱动返回的数据总获取一个zero-copy的slice byte。当下一次调用Next的时候,这个值就不在有效了,因为它指向的内存已经被驱动重写了别的数据。

Query使用的connection在所有的rows通过Next()遍历完后或者调用rows.Close()后释放。?

示例:

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

func init() {
db,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
}

func main() {
rows,err := Db.Query(<span style="color: #800000;">"<span style="color: #800000;">SELECT username,email FROM userinfo<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"query<span style="color: #800000;"> failed,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
<span style="color: #0000ff;">for rows.Next() { <span style="color: #008000;">//<span style="color: #008000;">循环结果
<span style="color: #0000ff;">var username,email <span style="color: #0000ff;">string<span style="color: #000000;">
err = rows.Scan(&username,&password,&<span style="color: #000000;">email)
println(username,email)
}

}
<span style="color: #008000;">//<span style="color: #008000;">wd 123 wd@163.com
<span style="color: #008000;">//<span style="color: #008000;">jack 1222 jack@165.com

Queryx和Query行为很相似,不过返回一个sqlx.Rows对象,支持扩展的scan行为,同时可将对数据进行结构体转换。

示例:

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

type stu <span style="color: #0000ff;">struct<span style="color: #000000;"> {
Username <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;username</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Password <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;password</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Department <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;department</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Email <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;email</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
}

func init() {
db,err := Db.Queryx(<span style="color: #800000;">"<span style="color: #800000;">SELECT username,email FROM userinfo<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">Qeryx failed,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
<span style="color: #0000ff;">for rows.Next() { <span style="color: #008000;">//<span style="color: #008000;">循环结果
<span style="color: #0000ff;">var<span style="color: #000000;"> stu1 stu
err = rows.StructScan(&<span style="color: #000000;">stu1)<span style="color: #008000;">// 转换为结构体
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">stuct data:<span style="color: #800000;">"<span style="color: #000000;">,stu1.Username,stu1.Password)
}
}
<span style="color: #008000;">//<span style="color: #008000;">stuct data: wd 123
<span style="color: #008000;">//<span style="color: #008000;">stuct data: jack 1222

QueryRow和QueryRowx都是从数据库中获取一条数据,但是QueryRowx提供scan扩展,可直接将结果转换为结构体。

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

type stu <span style="color: #0000ff;">struct<span style="color: #000000;"> {
Username <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;username</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Password <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;password</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Department <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;department</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Email <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;email</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
}

func init() {
db,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
}

func main() {
row := Db.QueryRow(<span style="color: #800000;">"<span style="color: #800000;">SELECT username,email FROM userinfo where uid = ?<span style="color: #800000;">",<span style="color: #800080;">1) <span style="color: #008000;">//<span style="color: #008000;"> QueryRow返回错误,错误通过Scan返回
<span style="color: #0000ff;">var username,email <span style="color: #0000ff;">string<span style="color: #000000;">
err :=row.Scan(&username,&<span style="color: #000000;">email)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil{
fmt.Println(err)
}
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">this is QueryRow res:[%s:%s:%s]n<span style="color: #800000;">"<span style="color: #000000;">,username,email)
<span style="color: #0000ff;">var<span style="color: #000000;"> s stu
err1 := Db.QueryRowx(<span style="color: #800000;">"<span style="color: #800000;">SELECT username,<span style="color: #800080;">2).StructScan(&<span style="color: #000000;">s)
<span style="color: #0000ff;">if err1 !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">QueryRowx error :<span style="color: #800000;">"<span style="color: #000000;">,err1)
}<span style="color: #0000ff;">else<span style="color: #000000;"> {
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">this is QueryRowx res:%v<span style="color: #800000;">"<span style="color: #000000;">,s)
}
}
<span style="color: #008000;">//<span style="color: #008000;">this is QueryRow res:[wd:123:wd@163.com]
<span style="color: #008000;">//<span style="color: #008000;">this is QueryRowx res:{jack 1222 jack@165.com}

Get和Select是一个非常省时的扩展,可直接将结果赋值给结构体,其内部封装了StructScan进行转化。Get用于获取单个结果然后Scan,Select用来获取结果切片。

示例:

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

type stu <span style="color: #0000ff;">struct<span style="color: #000000;"> {
Username <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;username</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Password <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;password</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Department <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;department</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
Email <span style="color: #0000ff;">string db:<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;email</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
}

func init() {
db,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
}

func main() {
<span style="color: #0000ff;">var<span style="color: #000000;"> stus []stu
err := Db.Select(&stus,<span style="color: #800000;">"<span style="color: #800000;">SELECT username,email FROM userinfo<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">Select error<span style="color: #800000;">"<span style="color: #000000;">,err)
}
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">this is Select res:%vn<span style="color: #800000;">"<span style="color: #000000;">,stus)
<span style="color: #0000ff;">var<span style="color: #000000;"> s stu
err1 := Db.Get(&s,<span style="color: #800080;">2<span style="color: #000000;">)
<span style="color: #0000ff;">if err1 !=<span style="color: #000000;"> nil{
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">GET error :<span style="color: #800000;">"<span style="color: #000000;">,err1)
}<span style="color: #0000ff;">else<span style="color: #000000;"> {
fmt.Printf(<span style="color: #800000;">"<span style="color: #800000;">this is GET res:%v<span style="color: #800000;">"<span style="color: #000000;">,s)
}
}
<span style="color: #008000;">//<span style="color: #008000;">this is Select res:[{wd 123 wd@163.com} {jack 1222 jack@165.com}]
<span style="color: #008000;">//<span style="color: #008000;">this is GET res:{jack 1222 jack@165.com}

事务(Transactions)

事务操作是通过三个方法实现:

Begin():开启事务

Commit():提交事务(执行sql)

Rollback():回滚

使用流程:

tx,err :===<span style="color: #008000;">//<span style="color: #008000;">或者使用sqlx扩展的事务
tx :=<span style="color: #000000;"> db.MustBegin()
tx.MustExec(...)
err = tx.Commit()

由于事务是一个一直连接的状态,所以Tx对象必须绑定和控制单个连接。一个Tx会在整个生命周期中保存一个连接,然后在调用commit或Rollback()的时候释放掉。在调用这几个函数的时候必须十分小心,否则连接会一直被占用直到被垃圾回收。?

使用示例:

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

func init() {
db,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
}

func main() {
tx,err :=<span style="color: #000000;"> Db.Beginx()
,err = tx.Exec(<span style="color: #800000;">"<span style="color: #800000;">insert into userinfo(username,password) values(?,<span style="color: #800000;">"<span style="color: #800000;">Rose<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">2223<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
tx.Rollback()
}
,<span style="color: #800000;">"<span style="color: #800000;">Mick<span style="color: #800000;">",<span style="color: #800080;">222<span style="color: #000000;">)
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">exec sql error:<span style="color: #800000;">"<span style="color: #000000;">,err)
tx.Rollback()
}
err =<span style="color: #000000;"> tx.Commit()
<span style="color: #0000ff;">if err !=<span style="color: #000000;"> nil {
fmt.Println(<span style="color: #800000;">"<span style="color: #800000;">commit error<span style="color: #800000;">"<span style="color: #000000;">)
}

}

连接池设置

默认情况下,连接池增长无限制,并且只要连接池中没有可用的空闲连接,就会创建连接。我们可以使用DB.SetMaxOpenConns设置池的最大大小。未使用的连接标记为空闲,如果不需要则关闭。要避免建立和关闭大量连接,可以使用DB.SetMaxIdleConns设置最大空闲连接。

注意:该设置方法golang版本至少为1.2

  • DB.SetMaxIdleConns(n int)? ? 设置最大空闲连接数
  • DB.SetMaxOpenConns(n int)? 设置最大打开的连接数

示例:

import (
_
<span style="color: #800000;">"<span style="color: #800000;">github.com/go-sql-driver/mysql<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">github.com/jmoiron/sqlx<span style="color: #800000;">"
<span style="color: #800000;">"<span style="color: #800000;">fmt<span style="color: #800000;">"<span style="color: #000000;">
)

<span style="color: #0000ff;">var Db *<span style="color: #000000;">sqlx.DB

func init() {
db,err)
<span style="color: #0000ff;">return<span style="color: #000000;">
}
Db =<span style="color: #000000;"> db
Db.SetMaxOpenConns(<span style="color: #800080;">30<span style="color: #000000;">)
Db.SetMaxIdleConns(<span style="color: #800080;">15<span style="color: #000000;">)

}

参考:http://jmoiron.github.io/sqlx/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!