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
+15.6k Golang : Validate hostname
+14.1k Golang : concatenate(combine) strings
+19.3k Golang : Populate dropdown with html/template example
+12.4k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+5.9k Cash Flow : 50 days to pay your credit card debt
+11.3k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+12.5k Golang : Search and extract certain XML data example
+15.9k Golang : How to login and logout with JWT example
+15.5k Golang : invalid character ',' looking for beginning of value
+22.1k Golang : Use TLS version 1.2 and enforce server security configuration over client
+6.7k Golang : Warp text string by number of characters or runes example
+5.9k Golang : Markov chains to predict probability of next state example