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
+20.4k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+8k Javascript : Read/parse JSON data from HTTP response
+17.4k Golang : Append content to a file
+12.5k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+17.8k Golang : Pipe output from one os.Exec(shell command) to another command
+22.1k Golang : Record voice(audio) from microphone to .WAV file
+4.3k Golang : Map within a map example
+9.7k Golang : Encrypt and decrypt data with x509 crypto
+4.4k Linux/Unix : Commands that you need to be careful about
+17.2k Golang : How to count the number of repeated characters in a string?
+15.2k Golang : When to use init() function?