Efficient Multi-Data Insertion in Go
Inserting multiple data rows simultaneously in SQL can significantly improve efficiency. In Go, you can achieve this using SQL's prepared statement and multiple values.
Consider the following data:
data := []map[string]string{ {"v1":"1", "v2":"1", "v3":"1"}, {"v1":"2", "v2":"2", "v3":"2"}, {"v1":"3", "v2":"3", "v3":"3"}, }
Instead of looping through the data and executing individual INSERT statements, you can use a prepared statement with values as follows:
sqlStr := "INSERT INTO test(n1, n2, n3) VALUES " vals := []interface{}{} for _, row := range data { sqlStr += "(?, ?, ?)," 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 preparing the SQL statement once and then executing it with all the values, you minimize the overhead of creating multiple prepared statements. Additionally, using interface{} as the type of vals allows you to insert any value type, providing flexibility and avoiding type conversions.
This approach is more efficient and safer than using string concatenation to construct the SQL query. Prepared statements prevent SQL injection vulnerabilities and improve the overall performance of your code when inserting multiple data rows simultaneously.
The above is the detailed content of How Can I Efficiently Insert Multiple Data Rows Simultaneously in Go Using SQL?. For more information, please follow other related articles on the PHP Chinese website!