在網(wǎng)上找了一大堆例子,最后簡(jiǎn)化一下把,一下會(huì)從安裝mysql開(kāi)始,與大家分享一下如何用go鏈接服務(wù)器上的mysql
我用的是ubuntu系統(tǒng)
1,安裝mysql:sudo apt-get install mysql-server (記住root的密碼假設(shè)密碼為root123)
2,進(jìn)入mysql:mysql -uroot -p 然后輸入密碼
3,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù):create database people;
4,給數(shù)據(jù)庫(kù)people添加用戶:GRANT ALL PRIVILEGES ON people.* TO peo@localhost IDENTIFIED BY "peo123";
5,調(diào)整數(shù)據(jù)庫(kù)配置以便于遠(yuǎn)程訪問(wèn):GRANT ALL PRIVILEGES ON people.* TO peo@“%” IDENTIFIED BY "peo123"; 然后推出mysql執(zhí)行:sudo nano /etc/mysql/my.cnf
修改bind-address=127.0.0.1 到bind-address= 機(jī)器的IP(就是安裝mysql的機(jī)器的ip)
6,重啟mysql:sudo /etc/init.d/mysql restart
7,建表:首先進(jìn)入mysql:mysql -u peo -p
進(jìn)入數(shù)據(jù)庫(kù)下: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ù)庫(kù)方面的工作已經(jīng)做好,接下來(lái)是go語(yǔ)言了
8,首先下載mysql的驅(qū)動(dòng)包(應(yīng)該是這樣叫)執(zhí)行 go get github.com/go-sql-driver/mysql代碼會(huì)下載到你的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")
}
至此結(jié)束
更多信息請(qǐng)查看IT技術(shù)專欄