在網上找了一大堆例子,最後簡化一下把,一下會從安裝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")
}
至此結束