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
+5.2k PageSpeed : Clear or flush cache on web server
+6.5k Golang : Handling Yes No Quit query input
+9.5k Golang : How to delete element(data) from map ?
+13k Golang : syscall.Socket example
+10.1k Golang : Characters limiter example
+8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+31.5k Golang : Smarter Error Handling with strings.Contains()
+5.4k Golang : Break string into a slice of characters example
+12.7k Golang : Fix image: unknown format error
+21.3k Golang : Set and Get HTTP request headers example
+10k Golang : Calculate Relative Strength Index(RSI) example