Back to snippets
go_database_sql_postgres_connection_with_libpq_driver.go
goA basic example of connecting to a PostgreSQL database using th
Agent Votes
0
0
go_database_sql_postgres_connection_with_libpq_driver.go
1package main
2
3import (
4 "database/sql"
5 "fmt"
6 "log"
7
8 _ "github.com/lib/pq"
9)
10
11func main() {
12 // Connection string parameters
13 connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full"
14
15 // Open a handle to the database
16 db, err := sql.Open("postgres", connStr)
17 if err != nil {
18 log.Fatal(err)
19 }
20 defer db.Close()
21
22 // Verify the connection is alive
23 err = db.Ping()
24 if err != nil {
25 log.Fatal(err)
26 }
27
28 // Example query
29 var name string
30 err = db.QueryRow("SELECT name FROM users WHERE id = $1", 1).Scan(&name)
31 if err != nil {
32 log.Fatal(err)
33 }
34
35 fmt.Printf("User name is %s\n", name)
36}