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 get github.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", 0, 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 } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。