This is a creation in Article, where the information may have evolved or changed.
http://blog.csdn.net/jesseyoung/article/details/40398321
Introduction to the Go language connection MySQL
Go official only offers two packages under the database Package,database package sql,sql/driver. The two packages are used to define the interface of the operational database, which ensures that regardless of which database is used, they operate the same way.
But go official does not provide the connection database driver, if you want to operate the database, but also need a third-party driver package, the most commonly used are:
Https://github.com/Go-SQL-Driver/MySQL Support Database/sql, all with Go write.
Https://github.com/ziutek/mymysql supports Database/sql, and also supports custom interfaces, all with go writing.
It is recommended to use the former, because the former is more efficient, the comparison between the two efficiency can refer to benchmark test results: Https://github.com/go-sql-driver/sql-benchmark
Go to connect to other mainstream database drive introduction can refer to:
https://code.google.com/p/go-wiki/wiki/SQLDrivers
2 Test environment preparation
Operating system: Red Hat Enterprise Linux Server Release 6.4
MySQL version: mysql-5.5.28
Install Git client (easy to get MySQL driver from GitHub)
[Plain] View plain copy
- [root@localhost/]# yum install git
Get MySQL Driver
[Plain] View plain copy
- [Root@localhost/]# Go get github.com/go-sql-driver/mysql
- [Root@localhost/]# ls
- Pkg src
You can see more than two folders in the current directory pkg and SRC, copy the src folder to the Go Program installation directory or go to work environment can be
[Plain] View plain copy
- [Root@localhost/]# cp-r src/usr/local/go/
3 Programming examples
[Plain] View plain copy
- Package Main
- Import (
- "Database/sql"
- "FMT"
- _ "Github.com/go-sql-driver/mysql"
- "Reflect"
- )
- Func Main () {
- /*DSN Data Source Name
- [username[:p assword]@] [Protocol[(address)]]/dbname[?param1=value1¶mn=valuen]
- User@unix (/path/to/socket)/dbname
- User:password@tcp (localhost:5555)/dbname?charset=utf8&autocommit=true
- USER:PASSWORD@TCP ([de:ad:be:ef::ca:fe]:80)/dbname?charset=utf8mb4,utf8
- User:password@/dbname
- No database: user:password@/
- */
- DB, err: = SQL. Open ("MySQL", "jesse:jesse@tcp (127.0.0.1:3306)/?charset=utf8")//The first parameter is the driver name
- Checkerr (ERR)
- Db. Query ("drop database if exists tmpdb")
- Db. Query ("CREATE Database Tmpdb")
- Db. Query ("Use tmpdb")
- Db. Query ("CREATE TABLE Tmpdb.tmptab (c1 int, C2 varchar (), C3 varchar (20))")
- Db. Query ("INSERT into Tmpdb.tmptab values (101, ' name 1 ', ' Address1 '), (102, ' Name 2 ', ' Address2 '), (103, ' name 3 ', ' ADDRESS3 '), (104, ' Name 4 ', ' Address4 ') ")
- Checkerr (ERR)
- Query, Err: = db. Query ("SELECT * from Tmpdb.tmptab")
- Checkerr (ERR)
- V: = reflect. ValueOf (query)
- Fmt. Println (v)
- Fmt. Println ("--increase data test--")
- Printresult (query)
- Db. Query ("Delete from Tmpdb.tmptab where C1 = 101")
- Checkerr (ERR)
- Query2, _: = db. Query ("SELECT * from Tmpdb.tmptab")
- Fmt. Println ("--delete data test--")
- Printresult (Query2)
- Db. Query ("Update Tmpdb.tmptab set c3 = ' Address4 ' WHERE C1 = 103")
- Checkerr (ERR)
- Query3, _: = db. Query ("SELECT * from Tmpdb.tmptab")
- Fmt. Println ("--Update data test--")
- Printresult (Query3)
- Db. Query ("Delete from Tmpdb.tmptab")
- Checkerr (ERR)
- Query4, _: = db. Query ("SELECT * from Tmpdb.tmptab")
- Fmt. Println ("--empty data test--")
- Printresult (Query4)
- Db. Query ("drop table Tmpdb.tmptab")
- Db. Query ("drop Database Tmpdb")
- stmt, err: = db. Prepare ("CREATE Database Tmpdb")
- Db. Close ()
- }
- Func Checkerr (errmasg error) {
- If ERRMASG! = Nil {
- Panic (ERRMASG)
- }
- }
- Func printresult (Query *sql. Rows) {
- Column, _: = Query. Columns ()//read out the queried column field name
- Values: = Make ([][]byte, Len (column))//values is the value of each column, obtained in byte
- Scans: = Make ([]interface{}, Len (column))//The length of the query is fixed with Len (column), because each query comes out of an indeterminate column
- For I: = range values {//Let each row of data populate [][]byte]
- Scans[i] = &values[i]
- }
- Results: = make (map[int]map[string]string)//Last obtained map
- I: = 0
- For query. Next () {//loop, let the cursor Move Down
- If err: = Query. Scan (Scans ...); Err! = Nil {//query. The indefinite Long value of the scan query is placed in scans[i] = &values[i], i.e. each line is placed in the values
- Fmt. PRINTLN (ERR)
- Return
- }
- Row: = Make (map[string]string)/per row of data
- For k, V: = range values {//each row of data is placed in values, now move it to row
- Key: = Column[k]
- Row[key] = string (v)
- }
- Results[i] = row//load in result set
- i++
- }
- For k, V: = Range Results {//Query out array
- Fmt. Println (k, v)
- }
- }
4 Running the program
4.1 Compiling and running
[Plain] View plain copy < param name= "allowfullscreen" value= "false" >< param name= "wmode" value= "Transparent" >
- [Root@localhost/]# Go Build mysqlgotest.go
- [Root@localhost/]# ls
- Mysqlgotest.go Mysqlgotest
- [Root@localhost/]#./mysqlgotest
4.2 Direct operation
[Plain] View plain copy
- [Root@localhost/]# Go Run mysqlgotest.go
- <*sql. Rows value>
- --Increase data testing--
- 0 map[c1:101 C2: Name 1 C3:address1]
- 1 map[c1:102 C2: Name 2 c3:address2]
- 2 map[c1:103 C2: Name 3 C3:ADDRESS3]
- 3 map[c1:104 C2: Name 4 C3:ADDRESS4]
- --Delete data test--
- 0 map[c1:102 C2: Name 2 c3:address2]
- 1 map[c1:103 C2: Name 3 C3:ADDRESS3]
- 2 map[c1:104 C2: Name 4 C3:ADDRESS4]
- --Update data test--
- 0 map[c1:102 C2: Name 2 c3:address2]
- 1 map[c1:103 C2: Name 3 C3:ADDRESS4]
- 2 map[c1:104 C2: Name 4 C3:ADDRESS4]
- --Empty data test--
5 Supplemental Knowledge
5.1 Avoid Chinese garbled characters
To ensure that the program is written to the database and read out from the database does not appear garbled, you need to do the following configuration: Go client program level: Go program File Settings encoding UTF8, such as
[Plain] View plain copy
- DB, err: = SQL. Open ("MySQL", "jesse:jesse@tcp (127.0.0.1:3306)/?charset=utf8")
MySQL database level:
Set MySQL database client and server configuration to UTF8
For example:
Configuring in the MY.CNF configuration file
[Plain] View plain copy < param name= "allowfullscreen" value= "false" >< param name= "wmode" value= "Transparent" >
- [MySQL]
- Default_character_set=utf8
- [Mysqld]
- Character-set-server=utf8
- Collation-server=utf8_bin
5.2 Go language reflection mechanism
Purpose: Can get Object data type
Many languages have a reflection mechanism. Through reflection, we can know an unknown property of the image, the method.
When writing a function, sometimes you need a different object or some property of the class, but the program does not recognize the object or class that is needed, and then it needs to be manipulated by reflection. By reflection, you become very convenient to load, detect, and use objects or classes that are completely unknown during compilation.
The so-called reflection, which is the equivalent of physical reflection, you can see your own touch through the mirror, the function through reflection, you can get the information you want. In Golang reflector reflect, the reflection type type () and value () can change the value of the reflected back variable. For example, gets the type of the variable value, which can be reflect by the function. ValueOf () to operate.
[Plain] View plain copy
- var value interface {} = &user{1, "Tom", "Nan"}
- V: = reflect. ValueOf (value)
- Fmt. Println (v)
****************************************************************************************
Original address: http://blog.csdn.net/jesseyoung/article/details/40398321
Blog home: http://blog.csdn.net/ Jesseyoung
****************************************************************************************