go語言怎麼和mysql資料庫進行連結

來源:互聯網
上載者:User

 在網上找了一大堆例子,最後簡化一下把,一下會從安裝mysql開始,與大家分享一下如何用go連結的伺服器上的mysql

我用的是ubuntu系統

1,安裝mysql:sudo apt-get install mysql-server (記住root的密碼假設密碼為root123)

2,進入mysql:mysql -uroot -p 然後輸入密碼

3,建立一個資料庫:create database people;

4,給資料庫people添加使用者:GRANT ALL PRIVILEGES ON people.* TO peo@localhost IDENTIFIED BY "peo123";

5,調整資料庫配置以便於遠端存取:GRANT ALL PRIVILEGES ON people.* TO peo@“%” IDENTIFIED BY "peo123"; 然後推出mysql執行:sudo nano /etc/mysql/my.cnf

修改bind-address=127.0.0.1 到bind-address= 機器的IP(就是安裝mysql的機器的ip)

6,重啟mysql:sudo /etc/init.d/mysql restart

7,建表:首先進入mysql:mysql -u peo -p

進入資料庫下:use people

建立表:create table hello(age int, name varchar(10));

插入一條資料:insert into hello(age, name) values(19, "hello world");

至此資料庫方面的工作已經做好,接下來是go語言了

8,首先下載mysql的驅動包(應該是這樣叫)執行 go get github.com/go-sql-driver/mysql代碼會下載到你的gopath下(執行export可以查看gopath)

接著就是下面的代碼了

package main
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
import "encoding/json"
import "fmt"


type User struct {
    Age     int `json:"age"`
    Name string `json:"name"`
}


func main() {
    fmt.Println("start")

    db, err := sql.Open("mysql", "peo:peo123@tcp(192.168.0.58:3306)/people?charset=utf8")
    if err != nil { 
       panic(err)
    }

    rows, err := db.Query("select age,name from hello")
    if err != nil {
       panic(err)
    }
    defer rows.Close()
 
    for rows.Next() {
        user := &User{}
        err = rows.Scan(&user.Age, &user.Name)
        if err != nil {
          painc(err)
        }
        b, _ := json.Marshal(user)
        fmt.Println(string(b)) 
    }
    println("end")
}
至此結束

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.