在网上找了一大堆例子,最后简化一下把,一下会从安装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")
}
至此结束
新闻热点
疑难解答