Created
October 11, 2018 22:44
-
-
Save unwosu/e2878ddc0cd337fc6660f4d048a31efa to your computer and use it in GitHub Desktop.
Bulk Insert with postgres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func BulkInsert(unsavedRows []*ExampleRowStruct) error { | |
valueStrings := make([]string, 0, len(unsavedRows)) | |
valueArgs := make([]interface{}, 0, len(unsavedRows) * 3) | |
i := 0 | |
for _, post := range unsavedRows { | |
valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d)", i*3+1, i*3+2, i*3+3)) | |
valueArgs = append(valueArgs, post.Column1) | |
valueArgs = append(valueArgs, post.Column2) | |
valueArgs = append(valueArgs, post.Column3) | |
i++ | |
} | |
stmt := fmt.Sprintf("INSERT INTO my_sample_table (column1, column2, column3) VALUES %s", strings.Join(valueStrings, ",")) | |
_, err := db.Exec(stmt, valueArgs...) | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment