0x00 引言
再简单的事情,也需要有人去做。
0x01 代码
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"os"
)
func main() {
type Person struct {
name string
age int
}
person := Person{"mike",18}
fmt.Println(person)
os.Remove("./foo.db")
db, err := sql.Open("sqlite3", "./foo.db")
checkErr(err)
defer db.Close()
//插入数据
_, err = db.Exec("create table userinfo (uid text not null primary key, username text, departname text, created text)")
checkErr(err)
stmt, err := db.Prepare("INSERT INTO userinfo(uid, username, departname, created) values(?,?,?,?)")
checkErr(err)
defer stmt.Close()
res, err := stmt.Exec("1", "astaxie", "研发部门", "2012-12-09")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
//更新数据
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)
defer stmt.Close()
res, err = stmt.Exec("astaxieupdate", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
//查询数据
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
defer rows.Close()
for rows.Next() {
var uid int
var username string
var department string
var created string
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
//删除数据
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)
defer stmt.Close()
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
0x02 错误处理
Golang 的这种检查错误的代码太多了,过度重复,一点都不优雅。Golang 2 对这种情况进行了改善。draft 给出的例子如下:
func main() {
hex, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
data, err := parseHexdump(string(hex))
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(data)
}
Golang 2的写法如下:
func main() {
handle err {
log.Fatal(err)
}
hex := check ioutil.ReadAll(os.Stdin)
data := check parseHexdump(string(hex))
os.Stdout.Write(data)
}
0x03 UPDATE
2019-01-15