How does the go language link to the mysql database?
I found a lot of examples on the Internet, and finally simplified it. I will start from installing mysql and share with you how to use go to link mysql on the server.
I use the ubuntu system.
1. install mysql: sudo apt-get install mysql-server (remember the root password and assume the password is root123)
2. Go to mysql: mysql-uroot-p and enter the password.
3. create a database: create database people;
4. Add a user TO the database people: grant all privileges on people. * TO peo @ localhost identified by "peo123 ";
5. Adjust the database configuration to facilitate remote access: grant all privileges on people. * TO peo @ "%" identified by "peo123"; then mysql execution is launched: sudo nano/etc/mysql/my. cnf
Modify bind-address = 127.0.0.1 to bind-address = IP address of the machine (that is, ip address of the machine on which mysql is installed)
6. restart mysql: sudo/etc/init. d/mysql restart.
7. Create a table: first enter mysql: mysql-u peo-p
Go to the database: use people
Create table hello (age int, name varchar (10 ));
Insert a data entry: insert into hello (age, name) values (19, "hello world ");
So far, the database work has been done well, and the next step is the go language.
8. First download the mysql driver package (which should be called this) and execute go get github.com/go-sql-driver/mysqlcode to download it to your gopathfile (execute export to view gopath)
The following code is displayed:
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 ")
}
End now