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
+11.3k Golang : Arithmetic operation with numerical slices or arrays example
+9.5k Swift : Convert (cast) String to Integer
+10k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+2k Golang : Fix go-cron set time not working issue
+5.9k Golang : Takes a plural word and makes it singular
+8.6k Golang : Eroding and dilating image with OpenCV example
+13.5k Golang : Normalize unicode strings for comparison purpose
+22.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+3.1k Golang : PGX CopyFrom to insert rows into Postgres database
+4.2k Golang : Constant and variable names in native language
+8.1k Golang : How to check if a string with spaces in between is numeric?