在 Golang 的世界,有定義資料庫存取的通用介面 database/sql ,但貌似官方沒有提供實作而是讓廣大的鄉民開發,並且標記哪些套件是有通過 go-sql-test 驗證的,因此,大部分就是挑哪些有標記的,或是直接看 github 有多熱門也行。
相關文件:
以下就連續動作,筆記一下。
程式碼:
package mainimport ("log""database/sql"_ "github.com/mattn/go-sqlite3")func main() {db, err := sql.Open("sqlite3", "/tmp/sqlite3.db")if err != nil {log.Fatalln(err)}defer db.Close()//// http://go-database-sql.org/modifying.html//// via db.Exec with checking the error message onlyif _, err := db.Exec(`CREATE TABLE IF NOT EXISTS account (uid INTEGER PRIMARY KEY AUTOINCREMENT,username VARCHAR(64) NULL);`); err != nil {log.Println(err)}// Insert via db.Prepareif stmt, err := db.Prepare("INSERT INTO account(username) VALUES(?)"); err == nil {if res, err := stmt.Exec("changyy.org"); err != nil {log.Println("Insert Exec Error:", err)} else if lastId, err := res.LastInsertId() ; err != nil {log.Println("Get LastInsertId Error:", err)} else if rowCount, err := res.RowsAffected() ; err != nil {log.Println("Get RowsAffected Error:", err)} else {log.Println("Insert Done, Last Insert Id:", lastId, ", RowsAffected: ", rowCount)// Update via db.Prepareif stmt, err := db.Prepare("UPDATE account SET username = ? WHERE uid = ?"); err != nil {log.Println("Update Prepqre Error:", err)} else if res, err := stmt.Exec("blog.changyy.org", lastId); err != nil {log.Println("Update Exec Error:", err)} else if rowCount, err := res.RowsAffected() ; err != nil {log.Println("Get RowsAffected Error:", err)} else {log.Println("Update RowsAffected: ", rowCount)}}} else {log.Println("Prepqre Insert Error:", err)}//// http://go-database-sql.org/retrieving.html// https://pkg.go.dev/database/sql#DB.Query//// via db.Query with sql.Rows and error mesasgerows, err := db.Query("SELECT * FROM account")if err != nil {log.Println(err)} else {defer rows.Close()log.Println("Result:")for rows.Next() {var id intvar username stringif err := rows.Scan(&id, &username) ; err == nil {log.Println(id, username)} else {log.Println(err)}}if err := rows.Err() ; err != nil {log.Println(err)}}}
執行:
% go run main.go2022/05/25 20:44:26 Insert Done, Last Insert Id: 1 , RowsAffected: 12022/05/25 20:44:26 Update RowsAffected: 12022/05/25 20:44:26 Result:2022/05/25 20:44:26 1 blog.changyy.org% file /tmp/sqlite3.db/tmp/sqlite3.db: SQLite 3.x database, last written using SQLite version 3038005, file counter 3, database pages 3, cookie 0x1, schema 4, UTF-8, version-valid-for 3% sqlite3 /tmp/sqlite3.db .schemaCREATE TABLE account (uid INTEGER PRIMARY KEY AUTOINCREMENT,username VARCHAR(64) NULL);CREATE TABLE sqlite_sequence(name,seq);
沒有留言:
張貼留言