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
+14.1k Golang : Reverse IP address for reverse DNS lookup example
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+14.5k Golang : How to determine if user agent is a mobile device example
+8k Golang : Handle Palindrome string with case sensitivity and unicode
+15.1k Golang : package is not in GOROOT during compilation
+9.5k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+48.6k Golang : Upload file from web browser to server
+12.1k Golang : Decompress zlib file example
+9.1k Golang : Handle sub domain with Gin
+20.5k Golang : Pipe output from one os.Exec(shell command) to another command
+6.1k Golang : Experimenting with the Rejang script
+15.9k Golang : Read a file line by line