5.2 MySQL

The LAMP stack has been very popular on the internet in recent years, and the M in LAMP stand for MySQL. MySQL is famous because it’s open source and easy to use. As such, it has become the de-facto database in the back-ends of many websites.

MySQL drivers

There are a couple of drivers that support MySQL in Go. Some of them implement the database/sql interface, and others use their own interface standards.

I’ll use the first driver in the following examples (I use this one in my personal projects too), and I also recommend that you use it for the following reasons:

  • It’s a new database driver and supports more features.
  • It fully supports database/sql interface standards.
  • Supports keep-alive, long connections with thread-safety.

Samples

In the following sections, I’ll use the same database table structure for different databases, then create SQL as follows:

  1. CREATE TABLE `userinfo` (
  2. `uid` INT(10) NOT NULL AUTO_INCREMENT,
  3. `username` VARCHAR(64) NULL DEFAULT NULL,
  4. `department` VARCHAR(64) NULL DEFAULT NULL,
  5. `created` DATE NULL DEFAULT NULL,
  6. PRIMARY KEY (`uid`)
  7. );

The following example shows how to operate on a database based on the database/sql interface standards.

  1. package main
  2. import (
  3. _ "github.com/go-sql-driver/mysql"
  4. "database/sql"
  5. "fmt"
  6. )
  7. func main() {
  8. db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
  9. checkErr(err)
  10. // insert
  11. stmt, err := db.Prepare("INSERT userinfo SET username=?,department=?,created=?")
  12. checkErr(err)
  13. res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
  14. checkErr(err)
  15. id, err := res.LastInsertId()
  16. checkErr(err)
  17. fmt.Println(id)
  18. // update
  19. stmt, err = db.Prepare("update userinfo set username=? where uid=?")
  20. checkErr(err)
  21. res, err = stmt.Exec("astaxieupdate", id)
  22. checkErr(err)
  23. affect, err := res.RowsAffected()
  24. checkErr(err)
  25. fmt.Println(affect)
  26. // query
  27. rows, err := db.Query("SELECT * FROM userinfo")
  28. checkErr(err)
  29. for rows.Next() {
  30. var uid int
  31. var username string
  32. var department string
  33. var created string
  34. err = rows.Scan(&uid, &username, &department, &created)
  35. checkErr(err)
  36. fmt.Println(uid)
  37. fmt.Println(username)
  38. fmt.Println(department)
  39. fmt.Println(created)
  40. }
  41. rows.Close()
  42. // delete
  43. stmt, err = db.Prepare("delete from userinfo where uid=?")
  44. checkErr(err)
  45. res, err = stmt.Exec(id)
  46. checkErr(err)
  47. affect, err = res.RowsAffected()
  48. checkErr(err)
  49. fmt.Println(affect)
  50. db.Close()
  51. }
  52. func checkErr(err error) {
  53. if err != nil {
  54. panic(err)
  55. }
  56. }

Let me explain a few of the important functions here:

  • sql.Open() opens a registered database driver. The Go-MySQL-Driver registered the mysql driver here. The second argument is the DSN (Data Source Name) that defines information pertaining to the database connection. It supports following formats:

    1. user@unix(/path/to/socket)/dbname?charset=utf8
    2. user:password@tcp(localhost:5555)/dbname?charset=utf8
    3. user:password@/dbname
    4. user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
  • db.Prepare() returns a SQL operation that is going to be executed. It also returns the execution status after executing SQL.

  • db.Query() executes SQL and returns a Rows result.
  • stmt.Exec() executes SQL that has been prepared and stored in Stmt.

Note that we use the format =? to pass arguments. This is necessary for preventing SQL injection attacks.