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
+10k Golang : Get login name from environment and prompt for password
+10.7k Golang : Removes punctuation or defined delimiter from the user's input
+5.3k Golang : Intercept, inject and replay HTTP traffics from web server
+18.4k Golang : Write file with io.WriteString
+8.9k Golang : automatically figure out array length(size) with three dots
+7.2k Golang : How to convert strange string to JSON with json.MarshalIndent
+17.6k Golang : Read data from config file and assign to variables
+13.3k Golang : error parsing regexp: invalid or unsupported Perl syntax
+10.7k Golang : Get UDP client IP address and differentiate clients by port number
+13.9k Golang : Google Drive API upload and rename example
+13.4k Golang : Get user input until a command or receive a word to stop