golang -- mysql & redis

前端之家收集整理的这篇文章主要介绍了golang -- mysql & redis前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

golang MysqL

驱动安装
go get github.com/go-sql-driver/MysqL
go install github.com/go-sql-driver/MysqL
以下是select的例子
package main

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

func main() {
    initMysqL("root:112358@tcp(192.168.6.234:3306)/test?charset=utf8")
    defer db.Close()

    // Prepare statement for select data
    stmtOut,err := db.Prepare("SELECT id,name FROM users WHERE name=?")
    checkErr(err)
    defer stmtOut.Close()

    // Execute the query
    rows,err := stmtOut.Query("zs")
    var id,name []byte

    for rows.Next() {
        // Scan the value to []byte
        err = rows.Scan(&id,&name)
        checkErr(err)

        // Use the string value
        fmt.Println(string(id),string(name))
    }

}

var db *sql.DB

func initMysqL(dbUrl string) {
    db,_ = sql.Open("MysqL",dbUrl)
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

/* result:
1 zs
2 zs
*/

其他sql语句:

// 插入
stmtIns,err := db.Prepare("INSERT INTO squareNum VALUES(?,?)") // ? = placeholder
res,err = stmtIns.Exec(i,(i * i)) // Insert tuples (i,i^2)
id,err := res.LastInsertId()

// 删除
stmtDel,err = db.Prepare("DELETE FROM userinfo WHERE uid=?")
res,err = stmtDel.Exec(id)
affect,err = res.RowsAffected()



golang redis

go redis client安装
go getgithub.com/hoisie/redis
go install github.com/hoisie/redis
package main

import (
	"fmt"
	"github.com/hoisie/redis"
	"sync"
)

func main() {
	initRedis()
	// 测试string
	client.Set("s",[]byte("hello world"))
	val,_ := client.Get("s")
	fmt.Println(string(val))
	client.Del("s")

	//测试list
	vals := []string{"a1","b2","c3","d4","e5"}
	for _,v := range vals {
		client.Rpush("l",[]byte(v))
	}
	dbvals,_ := client.Lrange("l",4)
	for i,v := range dbvals {
		println(i,":",string(v))
	}
	client.Del("l")
}

var (
	client *redis.Client
	mutex  sync.Mutex
)

func initRedis() {
	mutex.Lock()
	defer mutex.Unlock()
	if client != nil {
		return
	}
	client = &redis.Client{
		Addr:        "127.0.0.1:6379",Db:          0,Password:    "",MaxPoolSize: 10000,}
	if err := client.Auth(""); err != nil {
		fmt.Println("Auth:",err.Error())
		return
	}
}
原文链接:https://www.f2er.com/go/191156.html

猜你在找的Go相关文章