Home >Backend Development >Golang >How Can I Efficiently Insert Multiple Data Rows in Go?

How Can I Efficiently Insert Multiple Data Rows in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 07:36:10277browse

How Can I Efficiently Insert Multiple Data Rows in Go?

Efficient Multiple Data Insertion in Go

In database operations, it is often advantageous to insert multiple data rows simultaneously for efficiency reasons. Go provides several methods for achieving this.

One approach is to use the db.Prepare function to create a prepared statement. By using prepared statements, you can avoid SQL injection and improve performance. To insert multiple rows in a single execution using a prepared statement, follow these steps:

  1. Create an SQL string with the INSERT INTO statement and placeholders for the values. For example:
sqlStr := "INSERT INTO test(n1, n2, n3) VALUES (?, ?, ?)"
  1. Create a slice of maps to hold the data to be inserted:
data := []map[string]string{
   {"v1":"1", "v2":"1", "v3":"1"},
   {"v1":"2", "v2":"2", "v3":"2"},
   {"v1":"3", "v2":"3", "v3":"3"},
}
  1. Iterate over the slice and append the values to the prepared statement placeholders.
vals := []interface{}{}

for _, row := range data {
    vals = append(vals, row["v1"], row["v2"], row["v3"])
}
  1. Trimming the last comma from the sqlStr would be necessary to prepare the statement correctly:
//trim the last ,
sqlStr = sqlStr[0:len(sqlStr)-1]
  1. Prepare the statement with the updated sqlStr.
stmt, _ := db.Prepare(sqlStr)
  1. Execute the statement with the collected values:
res, _ := stmt.Exec(vals...)

By using this approach, you can efficiently insert multiple data rows into a database while ensuring safety and reducing the number of database executions.

The above is the detailed content of How Can I Efficiently Insert Multiple Data Rows in Go?. 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