Created
August 24, 2020 09:48
-
-
Save mutuadavid93/8a5e31fa81233669f90a7ee4e5b1c13d to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"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", "[email protected]") | |
err = row.Scan(&id) | |
if err != nil { | |
panic(err) | |
} | |
// Access dereferenced values from Scan() | |
fmt.Println("User id is ", id) | |
} |
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
Connect and Insert into PostgreSQL Database ::