This is a creation in Article, where the information may have evolved or changed.
After degrees Niang, found that more commonly used Golang MySQL driver package has two mymysql and Go-sql-driver/mysql. Personally feel that the name Mymysql is not elegant. So I chose the go-sql-driver/mysql.
1, the installation of Go-sql-driver/mysql
Because Go-sql-driver/mysql belongs to a third-party package, we need to get to this package first.
Add the installation package to our $gopath through the system's Shell tool (command line).
go get github.com/go-sql-driver/mysql
Note here: Use the above command not only to configure the Golang environment, but also to configure the Git bin directory in the PATH environment variable.
2. Operation MySQL
import ( "database/sql" _ "github.com/go-sql-driver/mysql")
Because we use the process, not directly to the go-sql-driver/mysql, but through the interface in the Database/sql to use the driver, this is the same as the idea of Java. So when we import the Go-sql-driver/mysql package, we use underscores as placeholders to tell Golang that the contents of this package will not be used directly.
Note:
If you import a package without using it, you will throw an error when building the program, such as imported and not Used:os, which follows the motto of Go: "No unnecessary code!" “。
The declaration of a variable, too, throws an error if you declare a variable without using the variable.
The presence of placeholders solves the problem of importing the package without explicitly using the package.
db, err := sql.Open("mysql""用户名:密码@/数据库名?charset=utf8")
The open function returns two values, but if we need only the DB value, regardless of the error, you can use a placeholder:
db, _:= sql.Open("mysql""用户名:密码@/数据库名?charset=utf8")
_, err := db.Exec(sql)
The EXEC function can execute a SQL that does not return, such as delete, UPDATE, insert operations.
- Prepare
Preprocessing a broken-down method to process SQL
Such as:
Increase:
err := db.Prepare(`INSERT user (user_name,user_age,user_sex) values (?,?,?)`)checkErr(errerr := stmt.Exec("tony"201)checkErr(errerr := res.LastInsertId()checkErr(err)
Modify:
errSET user_age=?,user_sex=? WHERE user_id=?`)checkErr(errerr := stmt.Exec(2121)checkErr(errerr := res.RowsAffected()checkErr(err)
Delete:
err := db.Prepare(`DELETE FROM user WHERE user_id=?`)checkErr(errerr := stmt.Exec(1)checkErr(errerr := res.RowsAffected()checkErr(err)
The query returns more than one record.
err := db.Query("select id,nickname from user") iferr != nil { fmt.Println(err.Error()) } defer rows.Close() for rows.Next() { int string rows.Scan(&id, &nickname) fmt.Println(nickname) } db.Close()
- Queryrow
The query returns a record.
row: = Open (). Queryrow ( "select Id,nickname from user where id=129986" ) var ID int var nickname string row. Scan (&id, &nickname)