Last active
July 7, 2023 20:21
-
-
Save cherryramatisdev/efa7e0bd74325be11b24c0d42f44771e to your computer and use it in GitHub Desktop.
A lot of data to postgres database with golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"os" | |
_ "github.com/lib/pq" | |
) | |
const ( | |
host = "localhost" | |
port = 5432 | |
user = "postgres" | |
password = "postgres" | |
dbname = "teste" | |
) | |
type File struct { | |
CouponCode string `json:"coupon_code"` | |
} | |
func main() { | |
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ | |
"password=%s dbname=%s sslmode=disable", | |
host, port, user, password, dbname) | |
db, err := sql.Open("postgres", psqlInfo) | |
if err != nil { | |
panic(err) | |
} | |
defer db.Close() | |
file, err := os.Open("data.json") | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
byteValue, _ := ioutil.ReadAll(file) | |
var fileData []File | |
json.Unmarshal(byteValue, &fileData) | |
sqlStr := "INSERT INTO partner_validation_code(code, partner_id, active) VALUES " | |
for _, row := range fileData { | |
sqlStr += fmt.Sprintf("('%s', 5, %t),", row.CouponCode, true) | |
} | |
//trim the last , | |
sqlStr = sqlStr[0 : len(sqlStr)-1] | |
fmt.Println(sqlStr) | |
// prepare the statement | |
db.Exec(sqlStr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment