Created
May 16, 2024 23:06
-
-
Save lalizita/ad5b2f44de78ae8ef67aea4374ad67a0 to your computer and use it in GitHub Desktop.
A fast script to test postgres connection
This file contains 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" | |
"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