在網(wǎng)上找了一大堆例子,最后簡化一下把,一下會從安裝mysql開始,與大家分享一下如何用go鏈接服務器上的mysql
我用的是ubuntu系統(tǒng)
1,安裝mysql:sudo apt-get install mysql-server (記住root的密碼假設密碼為root123)
2,進入mysql:mysql -uroot -p 然后輸入密碼
3,創(chuàng)建一個數(shù)據(jù)庫:create database people;
4,給數(shù)據(jù)庫people添加用戶:GRANT ALL PRIVILEGES ON people.* TO IDENTIFIED BY "peo123";
5,調整數(shù)據(jù)庫配置以便于遠程訪問:GRANT ALL PRIVILEGES ON people.* TO ” IDENTIFIED BY "peo123"; 然后推出mysql執(zhí)行: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
進入數(shù)據(jù)庫下:use people
創(chuàng)建表:create table hello(age int, name varchar(10));
插入一條數(shù)據(jù):insert into hello(age, name) values(19, "hello world");
至此數(shù)據(jù)庫方面的工作已經(jīng)做好,接下來是go語言了
8,首先下載mysql的驅動包(應該是這樣叫)執(zhí)行 go get github.com/go-sql-driver/mysql代碼會下載到你的gopath下(執(zhí)行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")
}
至此結束
更多信息請查看IT技術專欄