Golang Sqlite3 CRUD

Source: Internet
Author: User
Tags prepare

pacakge Main
Import ("Database/sql" "FMT" "Log" _ "Github.com/mattn/go-sqlite3" //sqlite3 dirver)//people has the database fieldsType peoplestruct{IDintnamestring Ageint}type AppContextstruct{db*SQL. Db}func Connectdb (DbNamestring) (*appcontext,string) {db, err:= SQL. Open ("Sqlite3", DbName)ifErr! =Nil {returnNil, err. Error ()}ifErr = db. Ping (); Err! =Nil {returnNil, err. Error ()}return&APPCONTEXT{DB},""}func (c*appContext) Getalldata () {rows, err:= C.db.query ("SELECT * from Users") ifErr! =Nil {fmt. Println (Err. Error ())return} defer rows. Close () forrows. Next () {p:=New(People) Err:= Rows. Scan (&p.id, &p.name, &p.age)ifErr! =Nil {fmt. PRINTLN (Err)} FMT. Println (P.id, P.name, P.age)}}//ADDFunc (c *AppContext) Add () {stmt, err:= C.db.prepare ("INSERT into users (name,age) values (?,?)") ifErr! =Nil {log. Fatal (ERR)} result, err:= stmt. Exec ("Jack",1) ifErr! =Nil {fmt. Printf ("Add error:%v", Err)return} LastID, err:=result. Lastinsertid ()ifErr! =Nil {log. Fatal (Err)} FMT. Println ("inserted ID is", LastID)}//DELETEFunc (c *AppContext) Delete () {stmt, err:= C.db.prepare ("DELETE from users WHERE id =?") ifErr! =Nil {log. Fatal (ERR)} result, err:= stmt. Exec (1) ifErr! =Nil {log. Fatal (Err)} Affectnum, err:=result. Rowsaffected ()ifErr! =Nil {log. Fatal (Err)} FMT. Println ("Delete affect rows is", Affectnum)}//UPDATEFunc (c *AppContext) Update () {stmt, err:= C.db.prepare ("UPDATE users SET age =? WHERE id =?") ifErr! =Nil {log. Fatal (ERR)} result, err:= stmt. Exec (Ten,1) ifErr! =Nil {log. Fatal (Err)} Affectnum, err:=result. Rowsaffected ()ifErr! =Nil {log. Fatal (Err)} FMT. Println ("update affect rows is", Affectnum)}//sqlite3 CRUDFunc Main () {C, err:= Connectdb ("abc.db") ifErr! =""{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!")}

Golang Sqlite3 CRUD

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.