@@ -49,31 +49,46 @@ func Example_batch() {
4949
5050 ctx := context .Background ()
5151
52- b := session .Batch (gocql .UnloggedBatch ).WithContext (ctx )
52+ // Example 1: Simple batch using the Query() method - recommended approach
53+ batch := session .Batch (gocql .LoggedBatch )
54+ batch .Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 2 , "1.2" )
55+ batch .Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 3 , "1.3" )
56+
57+ err = batch .ExecContext (ctx )
58+ if err != nil {
59+ log .Fatal (err )
60+ }
61+
62+ // Example 2: Advanced batch usage with Entries for more control
63+ b := session .Batch (gocql .UnloggedBatch )
5364 b .Entries = append (b .Entries , gocql.BatchEntry {
5465 Stmt : "INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" ,
55- Args : []interface {}{1 , 2 , "1.2 " },
66+ Args : []interface {}{1 , 4 , "1.4 " },
5667 Idempotent : true ,
5768 })
5869 b .Entries = append (b .Entries , gocql.BatchEntry {
5970 Stmt : "INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" ,
60- Args : []interface {}{1 , 3 , "1.3 " },
71+ Args : []interface {}{1 , 5 , "1.5 " },
6172 Idempotent : true ,
6273 })
6374
64- err = b .Exec ( )
75+ err = b .ExecContext ( ctx )
6576 if err != nil {
6677 log .Fatal (err )
6778 }
6879
69- err = b .Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 4 , "1.4" ).
70- Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 5 , "1.5" ).
71- Exec ()
80+ // Example 3: Fluent style chaining
81+ err = session .Batch (gocql .LoggedBatch ).
82+ Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 6 , "1.6" ).
83+ Query ("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)" , 1 , 7 , "1.7" ).
84+ ExecContext (ctx )
7285 if err != nil {
7386 log .Fatal (err )
7487 }
7588
76- scanner := session .Query ("SELECT pk, ck, description FROM example.batches" ).Iter ().Scanner ()
89+ // Verification: Display all inserted data
90+ fmt .Println ("All inserted data:" )
91+ scanner := session .Query ("SELECT pk, ck, description FROM example.batches" ).IterContext (ctx ).Scanner ()
7792 for scanner .Next () {
7893 var pk , ck int32
7994 var description string
@@ -83,8 +98,16 @@ func Example_batch() {
8398 }
8499 fmt .Println (pk , ck , description )
85100 }
101+
102+ if err := scanner .Err (); err != nil {
103+ log .Fatal (err )
104+ }
105+
106+ // All inserted data:
86107 // 1 2 1.2
87108 // 1 3 1.3
88109 // 1 4 1.4
89110 // 1 5 1.5
111+ // 1 6 1.6
112+ // 1 7 1.7
90113}
0 commit comments