SQL code snippets with golang js
Posted on March 2, 2022
Tags: sql
with simple postgres connection
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
)
func main() {
, err := pgx.Connect(context.Background(), "postgres://postgres@bserver.opnroot.com:8098/example")
connif err != nil {
.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
fmt.Exit(1)
os}
defer conn.Close(context.Background())
var greeting string
= conn.QueryRow(context.Background(), "INSERT INTO bleh (id,name,age) VALUES (1,'bob',30);").Scan(&greeting)
err if err != nil {
.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
fmt.Exit(1)
os}
.Println(greeting)
fmt}
with postgres pooling connection
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
:= "postgres://postgres@bserver.opnroot.com:8098/example"
dburl , err := pgxpool.New(context.Background(), dburl)
connif err != nil {
.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
fmt.Exit(1)
os}
defer conn.Close()
var greeting string
= conn.QueryRow(context.Background(), "INSERT INTO bleh (id,name,age) VALUES (3,'bob',30);").Scan(&greeting)
err if err != nil {
.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
fmt.Exit(1)
os}
.Println(greeting)
fmt}