时间:2021-07-01 10:21:17 帮助过:3人阅读
看下面Go程序是如何操作数据库表数据:增删改查
package main import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" ) func main() { db, err := sql.Open("sqlite3", "./foo.db") checkErr(err) //插入数据 stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)") checkErr(err) res, err := stmt.Exec("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) 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) 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) 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) } }
我们可以看到上面的代码和MySQL例子里面的代码几乎是一模一样的,唯一改变的就是导入的驱动改变了,然后调用sql.Open
是采用了SQLite的方式打开。
Go语言中使用SQLite数据库
标签: