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
+27.4k PHP : Count number of JSON items/objects
+7.3k Golang : How to stop user from directly running an executable file?
+33.5k Golang : convert(cast) bytes to string
+6.1k Unix/Linux : Use netstat to find out IP addresses served by your website server
+8.8k Golang : Capture text return from exec function example
+5.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+10.6k Golang : Command line file upload program to server example
+9.2k Facebook : Getting the friends list with PHP return JSON format
+8k Golang : Metaprogramming example of wrapping a function
+16.8k Golang : XML to JSON example
+9.6k Golang : ffmpeg with os/exec.Command() returns non-zero status
+6.2k Golang : Break string into a slice of characters example