Database/SQL Batching SQL Statements
Question:
In Java, batching SQL statements with the database/sql package is straightforward. How can you achieve similar functionality in Go?
: Answer:
The database/sql package in Go allows you to batch SQL statements using the db.Exec function, which takes a variable number of arguments. Here's how you can implement batching in Go:
Construct the SQL Statement:
Create a string that contains the SQL statement with placeholders for the values you want to insert. For example:
stmt := "INSERT INTO my_table (field1, field2, field3) VALUES (?, ?, ?)"
Explode the Arguments:
Create separate slices for the values you want to insert. For each row, append the values to these slices.
valueStrings := make([]string, 0, len(unsavedRows)) valueArgs := make([]interface{}, 0, len(unsavedRows) * 3) for _, post := range unsavedRows { valueStrings = append(valueStrings, "(?, ?, ?)") valueArgs = append(valueArgs, post.Field1) valueArgs = append(valueArgs, post.Field2) valueArgs = append(valueArgs, post.Field3) }
Execute the Batch:
Use the db.Exec function to execute the batched SQL statement, passing in the argument slices.
_, err := db.Exec(stmt, valueArgs...)
This method performs the batching operation in a single network roundtrip, making it efficient for inserting large amounts of data.
The above is the detailed content of How to Batch SQL Statements in Go's `database/sql` Package?. For more information, please follow other related articles on the PHP Chinese website!