Package Mainimport ("Database/sql" "FMT" "Log" _ "GITHUB.COM/LIB/PQ" //Postgres Driver)//People-databaseType peoplestruct{IDintnamestring Ageint}type AppContextstruct{db*SQL. DB}//connectdb Connect Specify DatabaseFunc Connectdb (drivernamestring, DbNamestring) (c *appcontext, errormessagestring) {db, err:=SQL. Open (drivername, DbName)ifErr! =Nil {returnNil, err. Error ()}ifErr = db. Ping (); Err! =Nil {returnNil, err. Error ()}return&APPCONTEXT{DB},""}//CreateFunc (c *AppContext) Create () {//Get Insert IDLastinsertid: =0ERR:= C.db.queryrow ("INSERT into Users (name,age) VALUES ($1,$2) Returning ID","Jack", A). Scan (&Lastinsertid)ifErr! =Nil {log. Fatal (Err)} FMT. Println ("inserted ID is", Lastinsertid)}//ReadFunc (c *AppContext) Read () {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)}}//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)}//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)}//Mypg-postgresql CRUDFunc Main () {C, err:= Connectdb ("Postgres","user=user1 password=password1 dbname=exampledb") defer c.db.close ()ifErr! =""{print (ERR)} c.create () fmt. Println ("Add Action done!") C.read () fmt. Println ("Get Action done!") c.update () fmt. Println ("Update Action done!") C.delete () fmt. Println ("Delete action done!")}
Golang PostgreSQL CRUD