先看数据库内容:
- mysql> select * from user;
- +----+--------+----------+
- | id | strKey | strValue |
- +----+--------+----------+
- | 1 | xxx | yyy |
- | 2 | xxx2 | yyy2 |
- | 3 | xxx | yyy3 |
- +----+--------+----------+
- 3 rows in set (0.00 sec)
用go来操作一下:
- package main
-
- import (
- "database/sql"
- "fmt"
-
- _ "github.com/go-sql-driver/mysql"
- )
-
- var DB *sql.DB
-
- func init() {
- var err error
- DB, err = sql.Open("mysql", "root@/taoge") // taoge is db name
- if err != nil {
- panic("heheda")
- }else{
- fmt.Println("Open ok")
- }
- }
-
- func get(key string) bool {
- sqlstr := "SELECT strKey, strValue FROM user where strKey = ?"
- stmt, err := DB.Prepare(sqlstr)
- defer stmt.Close()
- if err != nil {
- fmt.Println("Prepare error", err)
- return false
- }
-
- rows, err := stmt.Query(key)
- defer rows.Close()
- if err != nil {
- fmt.Println("Query error", err)
- return false
- }
-
- for rows.Next() {
- var key, val string
- err = rows.Scan(&key, &val)
- if err != nil {
- fmt.Println("Scan error", err)
- return false
- }
-
- fmt.Println("Result:", key, val)
- }
-
- return true
- }
-
- func main() {
- get("xxx")
- }
-
-
结果:
- Open ok
- Result: xxx yyy
- Result: xxx yyy3
如果是update操作, 那也简单, 无非就是用Exec而已。
创建数据库表的话, 可以这么玩:
- package main
-
- import (
- "database/sql"
- "fmt"
-
- _ "github.com/go-sql-driver/mysql"
- )
-
- var DB *sql.DB
-
- func init() {
- var err error
- DB, err = sql.Open("mysql", "root@/taoge") // taoge is db name
- if err != nil {
- }else{
- fmt.Println("Open ok")
- }
- }
-
- func main() {
- createTable()
- }
-
- func createTable() {
- prefix := "CREATE TABLE IF NOT EXISTS "
-
- sqlstr := prefix + "tb_people" + "(" + `
- id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
- name varchar(64) NOT NULL,
- addr varchar(64) NOT NULL
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 `
-
- fmt.Println(sqlstr)
-
- _, err := DB.Exec(sqlstr)
- if err != nil {
- fmt.Println(err)
- }
- }
-
-
自测OK.
不多说。