// Very simple example of getting data from postgres DB in GO // Prior to running this program you have to set things up so that // go knows how to use/do the github import // Two commands: at the command line in the directory in which this // code sits: // go mod init que.go // go get github.com/lib/pq package main import ( "database/sql" "fmt" _ "github.com/lib/pq" // _ means that this import is referred to as pq ) // the information needed to connect to the DB server. // Note localhost!!!! const ( host = "localhost" port = 5432 user = "dbuser" password = "12345678" dbname = "sakila" ) func main() { // connection string psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) // open database db, err := sql.Open("postgres", psqlconn) CheckError(err) // close database defer db.Close() // check db err = db.Ping() CheckError(err) fmt.Println("Connected!") getData(db) } // actually do a query func getData(db *sql.DB) { rows, err := db.Query("select first_name, last_name from actor where last_name like 'A%'") CheckError(err) defer rows.Close() for rows.Next() { var fn string var ln string err = rows.Scan(&fn, &ln) CheckError(err) fmt.Printf("First:%s last:%s\n", fn, ln); } } // very basic, and aggressive error handler. func CheckError(err error) { if err != nil { panic(err) } }