golang操作数据库

  在golang中操作非关系型数据库(redis)和关系型数据库(mysql)。

  首先是下载数据库驱动包,因为墙的缘故,可能下载驱动包会有超时连接失败的情况,可以将镜像站点设为国能知名站点

阿里云站点:
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/

  操作redis:

  下载驱动包

go get -u github.com/gomodule/redigo/redis

  开启redis服务端,代码里导入redis依赖即可,代码示例:

package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var pool *redis.Pool

func init() {
	pool = &redis.Pool{
		MaxIdle:     8,
		MaxActive:   0,
		IdleTimeout: 100,
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "localhost:6379")
		},
	}
}

func main() {
	conn := pool.Get()
	defer conn.Close()

	_, err := conn.Do("MSet", "name", "stu", "hobby", "coding")
	if err != nil {
		panic(err)
	}

	s, err := redis.String(conn.Do("Get", "name"))
	if err != nil {
		panic(err)
	}
	_, err = conn.Do("del", "name")
	if err != nil {
		panic(err)
	}
	fmt.Println(s)
}

  操作mysql

  下载驱动包

go get -u github.com/go-sql-driver/mysql

  同样导入依赖即可,代码示例

package main

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

func main() {
	open, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/ztgeo?parseTime=true")
	if err != nil {
		panic(err)
	}

	defer open.Close()

	query, err := open.Query("select id,user_id,depart_id,tenant_id from ztgeo.base_depart_user")
	if err != nil {
		panic(err)
	}
	fmt.Println(query)

	for query.Next() {
		var id string
		var userId sql.NullString
		var departId sql.NullString
		var tenantId string
		err := query.Scan(&id,&userId,&departId,&tenantId)
		if err != nil {
			panic(err)
		}
		fmt.Printf("id=%v  userId=%v departId=%v  tenantId=%v \n", id, userId, departId, tenantId)
	}
	query.Close()
}

  

上一篇:go笔记-goroutine和panic


下一篇:Kernel panic - not syncing: softlockup: hung tasks