Go official only provided the database Package,database package has two packages sql,sql/driver. These two packages are used to define the interfaces that manipulate the database, which ensures that they operate in the same way regardless of which database is used.
But go official does not provide the connection database driver, if wants to operate the database, also needs the third party driver package, fortunately, the mainstream database driver already has: https://code.google.com/p/go-wiki/wiki/SQLDrivers
Among them, MySQL has two packages, one is Mymysql, one is Go-sql-driver/mysql, two package are pure go implementation. I chose the latter, because the latter is a little more efficient, Benchmark here: Https://github.com/go-sql-driver/sql-benchmark
The use of SQL packages is straightforward:
1, establish the connection
The first is open,
Copy Code code as follows:
DB, err: = SQL. Open ("MySQL", "User:password@/dbname")
DB is a *sql. A pointer to the DB type, which is used in the following operation to use the DB
After open, no actual connection is established with the database, and the actual connection to the database is done by pinging. In addition, DB should exist throughout the life cycle of the program, that is, when the program starts, it obtains DB through open until the program is finished, and then close db, rather than often open/close.
Copy Code code as follows:
2. Basic usage
the main methods of DB are:
Query executes the query operation for the database, such as a SELECT statement, which returns *rows
Queryrow executes a database that returns up to 1 rows of query operations, returning *row
PrePare prepares a database query operation and returns a *stmt for subsequent query or execution. This stmt can be executed multiple times, or executed concurrently
Exec execution does not return any of the rows ' base statements, such as the delete operation
3. Simple example
Copy Code code as follows:
Package Main
Import (
"Database/sql"
"FMT"
_ "Github.com/go-sql-driver/mysql"
)
Type User struct {
ID int
Username, password string
}
var sqldata map[interface{}]interface{}
Func Main () {
var u User
DB, err: = SQL. Open ("MySQL", "Root:@/test?charset=utf8")
Check (ERR)
Inserting data
stmt, err: = db. Prepare ("INSERT user SET username=?,password=?")
Check (ERR)
Res, err: = stmt. Exec ("Xiaowei", "Xiaowei")
Check (ERR)
ID, Err: = Res. Lastinsertid ()
Check (ERR)
Fmt. PRINTLN (ID)
Querying data
Rows, err: = db. Query ("SELECT * from user")
Check (ERR)
Fmt. Println (rows. Columns ())
UserInfo: = Make (map[interface{}]interface{})
For rows. Next () {
ERR: = rows. Scan (&u.id, &u.username, &u.password)
Check (ERR)
Userinfo[u.id] = u
}
Fmt. Println (UserInfo)
}
Func Check (err error) {
If Err!= nil {
Fmt. PRINTLN (ERR)
}
}