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
+4.7k Fix yum-complete-transaction error
+6.2k Golang : Example of custom handler for Gorilla's Path usage.
+10.8k Golang : Determine if time variables have same calendar day
+19.2k PHP : Convert(cast) int to double/float
+16.4k Golang : Upload/Receive file progress indicator
+7.9k Golang : How to get username from email address
+14.8k Golang : Delete files by extension
+7.6k Golang : Executing and evaluating nested loop in html template
+16.1k Golang : When to use init() function?
+6.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+8.5k Golang : Eroding and dilating image with OpenCV example
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot