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
+11.4k Golang : Convert(cast) float to int
+14.8k Golang : How do I get the local IP (non-loopback) address ?
+18.8k Golang : Clearing slice
+13.3k Generate salted password with OpenSSL example
+5.6k Cash Flow : 50 days to pay your credit card debt
+6.8k Restart Apache or Nginx web server without password prompt
+9.6k Golang : Get current, epoch time and display by year, month and day
+25k Golang : Convert uint value to string type
+21.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+9k Golang : How to get username from email address
+5.1k PHP : Hide PHP version information from curl