package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
host = "localdocker"
port = 5432
user = "postgres"
password = "password"
dbname = "testDB"
)
func createTable(db *sql.DB) {
_, err := db.Exec(`
CREATE TABLE person (
id serial PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age integer DEFAULT 0
);`)
if err != nil {
panic(err)
}
fmt.Println("Finished creating table")
}
func deleteTable(db *sql.DB) {
_, err := db.Exec(`DROP TABLE IF EXISTS person;`)
if err != nil {
panic(err)
}
fmt.Println("Finished dropping table")
}
func insertData(db *sql.DB, name string, age int) {
sql_statement := "INSERT INTO person (name, age) VALUES ($1, $2);"
_, err := db.Exec(sql_statement, name, age)
if err != nil {
panic(err)
}
fmt.Println("Finished inserting data")
}
func queryTable(db *sql.DB) {
var id int
var name string
var age int
sql_statement := "SELECT * from person;"
rows, err := db.Query(sql_statement)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
switch err := rows.Scan(&id, &name, &age); err {
case sql.ErrNoRows:
fmt.Println("No rows were returned")
case nil:
fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age)
default:
if err != nil {
panic(err)
}
}
}
}
func updateData(db *sql.DB, id int, name string, age int) {
sql_statement := "UPDATE person SET name = $2, age = $3 WHERE id = $1;"
_, err := db.Exec(sql_statement, id, name, age)
if err != nil {
panic(err)
}
fmt.Println("Finished updating data")
}
func deleteData(db *sql.DB, id int) {
sql_statement := "DELETE FROM person WHERE id = $1;"
_, err := db.Exec(sql_statement, id)
if err != nil {
panic(err)
}
fmt.Println("Finished deleting data")
}
func main() {
connectionString := fmt.Sprintf("host=%s port=%d "+
"user=%s password=%s "+
"dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully created connection to database")
deleteTable(db)
createTable(db)
insertData(db, "Haha", 5)
insertData(db, "Yooo", 15)
insertData(db, "DaDa", 25)
queryTable(db)
updateData(db, 1, "Yaaaaaaaaaa", 100)
deleteData(db, 2)
queryTable(db)
}