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
+6.5k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+9.9k Golang : interface - when and where to use examples
+13k Golang : Convert IPv4 address to packed 32-bit binary format
+8.9k Golang : How to join strings?
+4.9k PHP : Extract part of a string starting from the middle
+12.7k Golang : Forwarding a local port to a remote server example
+7.8k Golang : Error reading timestamp with GORM or SQL driver
+22k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+7.6k Golang : Gorrila set route name and get the current route name
+6.2k Golang : Function as an argument type example
+26.5k Golang : Calculate future date with time.Add() function