@@ -15,6 +15,42 @@ type DummyTable struct {
15
15
Email string `json:"email"`
16
16
}
17
17
18
+ func executeEverythingInASingleTransacton (conn * pgx.Conn ) {
19
+
20
+ tx , err := conn .Begin (context .Background ())
21
+
22
+ if err != nil {
23
+ fmt .Fprintf (os .Stderr , "The erros while begining a transaction is \n %v" , err )
24
+ os .Exit (1 )
25
+ }
26
+
27
+ defer tx .Rollback (context .Background ())
28
+
29
+ row ,
err := tx .
Exec (
context .
Background (),
"INSERT INTO dummy_table(id, name, age, email) values($1, $2, $3, $4)" ,
18 ,
"Tula" ,
52 ,
"[email protected] " )
30
+
31
+ errRow ,
errorInSecondInsert := tx .
Exec (
context .
Background (),
"INSERT INTO dummy_table(id, name, age, email) values($1, $2, $3, $4)" ,
19 ,
"Ashneer" ,
57 ,
"[email protected] " )
32
+
33
+ if err != nil {
34
+ fmt .Fprintf (os .Stderr , "error while executing a transaction query \n %v" , err )
35
+ os .Exit (1 )
36
+ }
37
+
38
+ if errorInSecondInsert != nil {
39
+ fmt .Fprintf (os .Stderr , "error while executing a transaction query \n %v" , errorInSecondInsert )
40
+ os .Exit (1 )
41
+ }
42
+
43
+ fmt .Println ("Rows affected in this transaction" , row .RowsAffected (), errRow .RowsAffected ())
44
+
45
+ err = tx .Commit (context .Background ())
46
+
47
+ if err != nil {
48
+ fmt .Fprintf (os .Stderr , "The error while commiting is \n %v" , err )
49
+ os .Exit (1 )
50
+ }
51
+
52
+ }
53
+
18
54
func printAllRowsInTable (conn * pgx.Conn ) {
19
55
rows , err := conn .Query (context .Background (), "select * from dummy_table" )
20
56
@@ -109,6 +145,8 @@ func getDBConnectionHandler() *pgx.Conn {
109
145
110
146
func main () {
111
147
148
+ // Comment insert and update whenever needed
149
+
112
150
conn := getDBConnectionHandler ()
113
151
defer conn .Close (context .Background ())
114
152
@@ -127,4 +165,6 @@ func main() {
127
165
fmt .Println (("\n Deleting one row in dummy table" ))
128
166
printRowAfterDeleting (conn )
129
167
168
+ fmt .Println ("\n Executing in a single transaction" )
169
+ executeEverythingInASingleTransacton (conn )
130
170
}
0 commit comments