Skip to content

Instantly share code, notes, and snippets.

@mutuadavid93
Created August 24, 2020 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutuadavid93/8a5e31fa81233669f90a7ee4e5b1c13d to your computer and use it in GitHub Desktop.
Save mutuadavid93/8a5e31fa81233669f90a7ee4e5b1c13d to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
// Reference :: https://pkg.go.dev/github.com/lib/pq?tab=doc
// Create all PostgreSQL Database Configs
const (
host = "localhost"
port = 5432
dbname = "lenslocked_dev"
user = "streetmoney"
)
func main() {
driverName := "postgres"
// Note :: Remove the password database field in the psqlinfo below if it's empty
// otherwise psql will behave abnormally
psqlinfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable",
host, port, user, dbname)
// Note :: sql.OPen() doesn't connect to database, it only ensures the
// driver and datasource are valid
db, err := sql.Open(driverName, psqlinfo)
if err != nil {
panic(err)
}
defer db.Close()
var id int
// Do a database operation here
// Scan() will place the dereferenced value into our id variable.
row := db.QueryRow(`
INSERT INTO users (name, email)
VALUES($1, $2)
RETURNING id`, "Lonzo Ball", "lonzo@gmail.com")
err = row.Scan(&id)
if err != nil {
panic(err)
}
// Access dereferenced values from Scan()
fmt.Println("User id is ", id)
}
@mutuadavid93
Copy link
Author

mutuadavid93 commented Aug 24, 2020

Connect and Insert into PostgreSQL Database ::

  • A simple demonstration to connect PostgreSQL Database to Golang codebase 😂
  • Inserts a user into users table and returns the inserted record's id immediately

@mutuadavid93
Copy link
Author

Query for a single row.

  • Replace the code after defer.Close() line in the gist and rerun program.
        var id int
	var name, email string
	// Do a database operation here
	// Scan() will place the dereferenced value into our variables
	row := db.QueryRow(`
	SELECT id,name, email 
	FROM users	
	WHERE id=$1`, 5)
	err = row.Scan(&id, &name, &email)

	if err != nil {
		if err == sql.ErrNoRows {
			println("There is no row matching provided creteria")
		} else {
			panic(err)
		}
	}

	// Access dereferenced values from Scan()
	fmt.Printf("id : %v, name : %s, email : %s\n", id, name, email)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment