pacakge mainimport ( "database/sql" "fmt" "log" _ "github.com/mattn/go-sqlite3" // sqlite3 dirver ) // People have database fields type People struct { id int name string age int } type appContext struct { db *sql.DB } func connectDB(dbName string) (*appContext, string) { db, err := sql.Open("sqlite3", dbName) if err != nil { return nil, err.Error() } if err = db.Ping(); err != nil { return nil, err.Error() } return &appContext{db}, "" } func (c *appContext) getAllData() { rows, err := c.db.Query("SELECT * FROM users") if err != nil { fmt.Println(err.Error()) return } defer rows.Close() for rows.Next() { p := new(People) err := rows.Scan(&p.id, &p.name, &p.age) if err != nil { fmt.Println(err) } fmt.Println(p.id, p.name, p.age) } } // ADD func (c *appContext) Add() { stmt, err := c.db.Prepare("INSERT INTO users(name,age) values(?,?)") if err != nil { log.Fatal(err) } result, err := stmt.Exec("Jack", 1) if err != nil { fmt.Printf("add error: %v", err) return } lastID, err := result.LastInsertId() if err != nil { log.Fatal(err) } fmt.Println("inserted id is ", lastID) } // DELETE func (c *appContext) Delete() { stmt, err := c.db.Prepare("DELETE FROM users WHERE id = ?") if err != nil { log.Fatal(err) } result, err := stmt.Exec(1) if err != nil { log.Fatal(err) } affectNum, err := result.RowsAffected() if err != nil { log.Fatal(err) } fmt.Println("delete affect rows is ", affectNum) } // UPDATE func (c *appContext) Update() { stmt, err := c.db.Prepare("UPDATE users SET age = ? WHERE id = ?") if err != nil { log.Fatal(err) } result, err := stmt.Exec(10, 1) if err != nil { log.Fatal(err) } affectNum, err := result.RowsAffected() if err != nil { log.Fatal(err) } fmt.Println("update affect rows is ", affectNum) } // sqlite3 CRUD func main() { c, err := connectDB("abc.db") if err != "" { print(err) } c.getAllData() fmt.Println("get action done!") c.Add() fmt.Println("add action done!") c.Delete() fmt.Println("delete action done!") c.Update() fmt.Println("update action done!") }
时间: 2024-10-08 21:46:18