Home >Backend Development >Golang >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:
sqlStr := "INSERT INTO test(n1, n2, n3) VALUES (?, ?, ?)"
data := []map[string]string{ {"v1":"1", "v2":"1", "v3":"1"}, {"v1":"2", "v2":"2", "v3":"2"}, {"v1":"3", "v2":"3", "v3":"3"}, }
vals := []interface{}{} for _, row := range data { vals = append(vals, row["v1"], row["v2"], row["v3"]) }
//trim the last , sqlStr = sqlStr[0:len(sqlStr)-1]
stmt, _ := db.Prepare(sqlStr)
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!