Home >Backend Development >Golang >How to Batch SQL Statements Efficiently Using Go's database/sql Package?

How to Batch SQL Statements Efficiently Using Go's database/sql Package?

DDD
DDDOriginal
2024-12-26 13:31:10941browse

How to Batch SQL Statements Efficiently Using Go's database/sql Package?

Batching SQL Statements with the Go database/sql Package

In Java, executing multiple SQL statements in a batch can be achieved through the PreparedStatement and executeBatch() method. But how can we accomplish the same using Go's database/sql package?

The database/sql package provides a Exec function that can execute SQL statements. However, it only takes a single set of arguments. To batch multiple statements, we can use a variadic function and construct a single SQL statement that includes all the individual statements to be executed.

Here's an example:

func bulkInsert(unsavedRows []*ExampleRowStruct) error {
    var (
        valueStrings []string
        valueArgs    []interface{}
    )

    for _, post := range unsavedRows {
        valueStrings = append(valueStrings, "(?, ?, ?)")
        valueArgs = append(valueArgs, post.Column1)
        valueArgs = append(valueArgs, post.Column2)
        valueArgs = append(valueArgs, post.Column3)
    }

    stmt := fmt.Sprintf(
        "INSERT INTO my_sample_table (column1, column2, column3) VALUES %s",
        strings.Join(valueStrings, ","),
    )

    _, err := db.Exec(stmt, valueArgs...)
    return err
}

This code constructs a single SQL statement that inserts all the rows into the database. By passing the individual statement arguments (values) as variadic parameters, we can execute multiple statements in a single network roundtrip. Tests have shown that this approach can be significantly faster than using the Begin, Prepare, and Commit methods for batching SQL statements.

The above is the detailed content of How to Batch SQL Statements Efficiently Using Go's database/sql Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn