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