Find a lot of examples on the Internet, and finally simplify the put, will start from the installation of MySQL, and share with you how to use the Go link server MySQL
I'm using the Ubuntu system.
1, install Mysql:sudo apt-get install Mysql-server (remember the password for root to assume the password is root123)
2, enter the mysql:mysql-uroot-p and enter the password.
3, creating a database: Create DB people;
4, add users to the database people: GRANT all privileges on people.* to Peo@localhost identified by "peo123";
5, adjust the database configuration for easy remote access: GRANT all privileges on people.* to peo@ "%" identified by "peo123"; Then launch MySQL execution: sudo nano/etc/mysql/my.cnf
Modify the IP of the bind-address=127.0.0.1 to the bind-address= machine (the IP that installs the MySQL machine)
6, restart Mysql:sudo/etc/init.d/mysql restart
7, build the table: first into the mysql:mysql-u peo-p
Access to the database: use people
Creating table: Create table Hello (age int, name varchar (10));
Inserts a piece of data: INSERT into Hello (age, name) VALUES ("Hello World");
This database work has been done, followed by the Go language
8, first download the MySQL driver package (which is supposed to be called) Execute go get github.com/go-sql-driver/mysql code will download to your Gopath (run export can view Gopath)
The
is followed by the following code
Package main
Import "Database/sql"
Import _ "github.com/go-sql-driver/mysql"
Import "Encoding/json"
Import ' FMT '
type User struct {
age int ' json: ' Age '
&nbs p; 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) br> }
defer rows. Close ()
for rows. Next () {
User: = &user{}
err = ro Ws. Scan (; user. Age, &user. Name
If err!= nil {
painc (er R)
}
B, _: = json. Marshal (user)
FMT. Println (string (b))
}
Println ("End")
}
This concludes