Skip to content

Instantly share code, notes, and snippets.

@lalizita
Created May 16, 2024 23:06
Show Gist options
  • Save lalizita/ad5b2f44de78ae8ef67aea4374ad67a0 to your computer and use it in GitHub Desktop.
Save lalizita/ad5b2f44de78ae8ef67aea4374ad67a0 to your computer and use it in GitHub Desktop.
A fast script to test postgres connection
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq" // Importando driver PostgreSQL
)
func main() {
// Abrindo conexão com o banco de dados
db, err := sql.Open("postgres", "user=postgres password=12345678 dbname=database host=localhost port=5432 sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close() // Fechando a conexão no final do programa
// Executando consulta SELECT na tabela "classes"
rows, err := db.Query("SELECT * FROM public.courses")
if err != nil {
log.Fatal(err)
}
defer rows.Close() // Fechando o conjunto de resultados no final da consulta
// Imprimindo os resultados da consulta
for rows.Next() {
var id int
var name string
var description string
err := rows.Scan(&id, &name, &description)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID: %d, Nome: %s, Descrição: %s\n", id, name, description)
}
// Verificando se todos os resultados foram processados
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment