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
+6.1k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+12k Golang : Decompress zlib file example
+18.4k Golang : Aligning strings to right, left and center with fill example
+9.6k Golang : Copy map(hash table) example
+5.7k Linux/Unix/PHP : Restart PHP-FPM
+12.6k Golang : Add ASCII art to command line application launching process
+12.7k Swift : Convert (cast) Int or int32 value to CGFloat
+20.3k nginx: [emerg] unknown directive "passenger_enabled"
+7k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.6k Gogland : Where to put source code files in package directory for rookie
+5.9k Golang : Function as an argument type example
+16.7k Golang : Read integer from file into array