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
+9.7k Golang : Translate language with language package example
+22.4k Golang : untar or extract tar ball archive example
+7.6k Golang : Get today's weekday name and calculate target day distance example
+5.1k Swift : Convert string array to array example
+18.8k Golang : Calculate entire request body length during run time
+9.6k Golang : Get current, epoch time and display by year, month and day
+6.3k Golang : Map within a map example
+5.5k Linux/Unix/PHP : Restart PHP-FPM
+21.5k Golang : How to reverse slice or array elements order
+18.8k Golang : Clearing slice
+6.4k Golang : Warp text string by number of characters or runes example
+10.7k Golang : Simple image viewer with Go-GTK