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
+35.4k Golang : Converting a negative number to positive number
+25.4k Golang : missing Mercurial command
+19.4k Golang : Archive directory with tar and gzip
+5.2k How to check with curl if my website or the asset is gzipped ?
+6.8k Golang : Validate credit card example
+9.8k Golang : Bcrypting password
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+15.1k Golang : rune literal not terminated error
+5.6k Golang : Function as an argument type example
+5.5k Unix/Linux : How to test user agents blocked successfully ?
+7.1k Android Studio : How to detect camera, activate and capture example
+17.5k Golang : How to log each HTTP request to your web server?