golang -- mysql & redis

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.