Golang : PGX CopyFrom to insert rows into Postgres database
Here is an example of how to use PGX's CopyFrom function to insert rows into Postgres database. The HScodes table is for my own reference, you will need to substitute it with your own table and struct.
Here you go!
type HScodes struct {
Sid int `json:"sid" db:"sid"`
HScode string `json:"name" db:"hscode"`
Keyword string `json:"value" db:"keyword"`
}
var dataToInsert []models.HScodes
rowsToInsert := [][]interface{}{}
for i := 0; i < len(dataToInsert); i++ {
row := []interface{}{dataToInsert[i].HScode, dataToInsert[i].Keyword}
rowsToInsert = append(rowsToInsert, row)
}
copyCount, err := database.WrapCopyFrom(ctx, pgx.Identifier{"hscodes"},
[]string{"hscode", "keyword"},
pgx.CopyFromRows(rowsToInsert))
Happy coding!
Reference :
See also : Golang : Trim everything onward after a word
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.4k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+5.8k Golang : Detect words using using consecutive letters in a given string
+14k Golang : Convert spaces to tabs and back to spaces example
+17.6k Golang : Check if IP address is version 4 or 6
+7.4k Golang : alternative to os.Exit() function
+7.9k Gogland : Where to put source code files in package directory for rookie
+8k Golang : Example of how to detect which type of script a word belongs to
+11.6k Golang : Change date format to yyyy-mm-dd
+6.9k Golang : Humanize and Titleize functions
+22k Golang : How to reverse slice or array elements order
+10.3k Golang : Identifying Golang HTTP client request