這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
golang mysql
驅動安裝
go get github.com/go-sql-driver/mysql
go install github.com/go-sql-driver/mysql
以下是select的例子
package mainimport ( "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.DBfunc initMySQL(dbUrl string) { db, _ = sql.Open("mysql", dbUrl)}func checkErr(err error) { if err != nil { panic(err) }}/* result:1 zs2 zs*/
其他sql語句:
// 插入stmtIns, err := db.Prepare("INSERT INTO squareNum VALUES(?, ?)") // ? = placeholderres, 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 mainimport ("fmt""github.com/hoisie/redis""sync")func main() {initRedis()// 測試stringclient.Set("s", []byte("hello world"))val, _ := client.Get("s")fmt.Println(string(val))client.Del("s")//測試listvals := []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.Clientmutex 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}}