昨天安裝了MySQL Driver, 也做了基本的測試.
今天來看應用.
首先在MySQL 建立一個 ironman1014的Table,為了詳細測試起見,
我們除了char型態以外,還安排了 timestamp, date 型態.
CREATE TABLE ironman1014(
uid SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name CHAR(10) NOT NULL,
cutime TIMESTAMP NOT NULL DEFAULT NOW(),
tdate DATE NOT NULL,
tdatachr CHAR(12) NOT NULL
);
Golang程式如下:
// hello64
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
var uid int
var name string
var cutime string
var tdate string
var tdatachr string
// Create Connection
db, err := sql.Open("mysql", "julia:julia@/julia?charset=utf8")
checkErr(err)
// Insert
stmt, err := db.Prepare("INSERT ironman1014 SET name=?, tdate=?, tdatachr=?")
checkErr(err)
res, err := stmt.Exec("bunko", "2014-10-14", "測試資料")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println("Last Insert ID: ", id)
fmt.Println("Insert Completed!")
fmt.Println("---------------")
// Update
stmt, err = db.Prepare("UPDATE ironman1014 SET name=? WHERE uid=?")
checkErr(err)
res, err = stmt.Exec("Bunko", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println("Affect: ", affect)
fmt.Println("Update Completed!")
fmt.Println("---------------")
// Query
rows, err := db.Query("SELECT uid, name, cutime, DATE_FORMAT(tdate, '%Y-%m-%d'), tdatachr FROM ironman1014")
checkErr(err)
for rows.Next() {
err = rows.Scan(&uid, &name, &cutime, &tdate, &tdatachr)
checkErr(err)
fmt.Println(uid)
fmt.Println(name)
fmt.Println(cutime)
fmt.Println(tdate)
fmt.Println(tdatachr)
fmt.Println("---------------")
}
fmt.Println("Query Completed!")
// Close Connection
db.Close()
fmt.Println("Close Connection and Quit Program!")
}
執行結果:
./hello64
Last Insert ID: 1
Insert Completed!
---------------
Affect: 1
Update Completed!
---------------
1
Bunko
2014-10-14 21:03:57
2014-10-14
測試資料
---------------
Query Completed!
Close Connection and Quit Program!
順利的 insert, 查詢last insert id, 再根據此id做update,
最後再做select,本例中雖然只insert 一筆,但是意義相同,
並且做適當的資料型態轉換.