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
+12k Golang : Print UTF-8 fonts on image example
+13.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+13.1k Golang : Increment string example
+5.8k Javascript : Get operating system and browser information
+39.2k Golang : Remove dashes(or any character) from string
+29k Golang : Record voice(audio) from microphone to .WAV file
+9.6k Golang : Function wrapper that takes arguments and return result example
+9.1k Golang : Find the length of big.Int variable example
+16.2k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+10.8k Golang : Read until certain character to break for loop