This is a creation in Article, where the information may have evolved or changed.
Introduced
Go-mysql is a go-write MySQL driver, using interface similar to go itself database SQL, but a little bit different, at this stage is not support integration into Go database/sql, but the implementation is not very difficult, the subsequent may be connected.
Go-mysql first started in mixer (a MySQL proxy with Go), with the evolution of mixer, I felt it necessary to use its MySQL module independently. For mixer, follow-up I will describe in detail.
Why should you implement a new set of interfaces instead of the SQL interface of Go itself? The main reason is that I'm not used to querying query methods. Go's own query example:
age := 27rows, err := db.Query("SELECT name FROM users WHERE age=?", age)if err != nil { log.Fatal(err)}for rows.Next() { var name string if err := rows.Scan(&name); err != nil { log.Fatal(err) } fmt.Printf("%s is %d\n", name, age)}if err := rows.Err(); err != nil { log.Fatal(err)}
As you can see, it is very cumbersome and complex to use, if the code inside the SELECT statement a lot (just our code inside n multiple Select), then if every time the select to get the results we need, then I may write code will write crash. So we are bound to provide a package to simplify the acquisition of the result set for select.
Resultset
Go-mysql the biggest SQL interface with go itself is the return of a resultset directly to query, and this resultset is defined as follows:
type Field struct { Name []byte Type uint8 Flag uint16}type Resultset struct { Status uint16 //server status for this query resultset Fields []Field FieldNames map[string]int Data [][]interface{}}
field is used to represent the name, data type, and some specific flags of the data returned at the time of the query. The data in resultset, however, is the actual information stored in the query results. Because for MySQL Select, it returns a result set of "m x n" and we use [][]interface{} to represent it directly in go.
The resultset provides a very convenient interface for the acquisition of select data:
//指定某一行,某一列获取数据,结果为stringfunc (r *Resultset) GetString(row, column int) (string, error)//执行某一行,某一列的名字获取数据,结果为stringfunc (r *Resultset) GetStringByName(row int, columnName int) (string, error)
Interface
Go-mysql provides almost the same interface usage as go database/sql in addition to query:
//Create a DB, maximum allowable keepalive 16 idle Connections//DSN format is:<username>:<password>@
Not only that, Go-mysql also provides separate access to a conn for external use, such as:
conn, err := db.GetConn()//我需要设置conn的字符集为gb2312conn.SetCharset("gb2312") conn.Close()
As you can see, the use of Go-mysql is very simple, it is gradually being used in our project and we are looking forward to your feedback.