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
+7.4k Golang : Get today's weekday name and calculate target day distance example
+17.1k Golang : [json: cannot unmarshal object into Go value of type]
+11.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+14.8k nginx: [emerg] unknown directive "ssl"
+7.9k Swift : Convert (cast) Character to Integer?
+8.8k Golang : Write multiple lines or divide string into multiple lines
+20.2k Golang : Saving private and public key to files
+10.1k Golang : ISO8601 Duration Parser example
+12.4k Golang : Get terminal width and height example
+29.2k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+30.6k Golang : bufio.NewReader.ReadLine to read file line by line
+5.8k Linux/Unix : Commands that you need to be careful about