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
+8k Golang : How to generate Code 39 barcode?
+7k Golang : Generate Datamatrix barcode
+5.8k Web : How to see your website from different countries?
+27.9k Golang : Calculate percentage change of two values
+32.9k Golang : Upload and download file to/from AWS S3
+6.8k Golang : Reverse text lines or flip line order example
+17k Golang : Populate dropdown with html/template example
+7.6k Golang : Generate EAN barcode
+18.2k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+9.9k Golang : Post data with url.Values{}
+11.3k Python : Convert IPv6 address to decimal and back to IPv6
+5.2k Golang : Embedded or data bundling example