# Connecting with Go

This guide explains how to establish a connection between a **Go (Golang)** application and a **PostgreSQL** database using the `github.com/lib/pq` driver. It walks through the necessary setup, configuration, and execution of a simple SQL query.

### **Variables**

To connect to a PostgreSQL database, you only need one environment variable — the **connection URI**. This URI contains all the necessary information like username, password, host, port, and database name.

<div class="overflow-x-auto contain-inline-size" id="bkmrk-variable-description"><table border="1" data-end="1005" data-start="750" style="border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead data-end="786" data-start="750"><tr data-end="786" data-start="750"><th data-end="761" data-start="750" style="border-color: rgb(0, 0, 0);">Variable</th><th data-end="775" data-start="761" style="border-color: rgb(0, 0, 0);">Description</th><th data-end="786" data-start="775" style="border-color: rgb(0, 0, 0);">Purpose</th></tr></thead><tbody data-end="1005" data-start="824"><tr data-end="1005" data-start="824"><td style="border-color: rgb(0, 0, 0);">**POSTGRESQL\_URI**</td><td style="border-color: rgb(0, 0, 0);">Full PostgreSQL connection string (from the Elestio service overview page)</td><td style="border-color: rgb(0, 0, 0);">Provides all necessary credentials and endpoint details in a single URI format.</td></tr></tbody></table>

</div>The URI will look like this:

```bash
postgresql://<USER>:<PASSWORD>@<HOST>:<PORT>/<DATABASE>
```

You can find the details needed in the URI from the **Elestio service overview** details. Copy and replace the variables carefully in the URI example provided above.

![image.png](https://docs.elest.io/uploads/images/gallery/2025-03/scaled-1680-/ZvEimage.png)

### **Prerequisites**

##### **Install Go**

Check if Go is installed by running:

```bash
go version
```

If not installed, download and install it from [https://go.dev/dl/](https://go.dev/dl/).

##### **Install `pq` Package**

Install the `pq` driver using:

```bash
go get github.com/lib/pq
```

### **Code**

Once all prerequisites are set up, create a new file named `main.go` and add the following code, and replace the `POSTGRESQL_URI` with actual link or in environment setup as you wish:

```go
package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/url"

	_ "github.com/lib/pq"
)

func getDBConnection(connectionString string) (*sql.DB, error) {
	parsedURL, err := url.Parse(connectionString)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse connection string: %v", err)
	}

	db, err := sql.Open("postgres", parsedURL.String())
	if err != nil {
		return nil, fmt.Errorf("Failed to open database connection: %v", err)
	}

	return db, nil
}

func main() {
	connectionString := "POSTGRESQL_URI"

	db, err := getDBConnection(connectionString)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	query := "SELECT current_database(), current_user, version()"
	rows, err := db.Query(query)
	if err != nil {
		log.Fatal("Failed to execute query:", err)
	}
	defer rows.Close()

	for rows.Next() {
		var dbName, user, version string
		if err := rows.Scan(&dbName, &user, &version); err != nil {
			log.Fatal("Failed to scan row:", err)
		}
		fmt.Printf("Database: %s\nUser: %s\nVersion: %s\n", dbName, user, version)
	}
}

```

To execute the script, open the terminal or command prompt and navigate to the directory where `main.go`. Once in the correct directory, run the script with the command

```bash
go run main.go
```

If the connection is successful, the terminal will display output similar to:

```
Database: Elestio
User: postgres
Version: PostgreSQL 16.8 (Debian 16.8-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
```

<div id="bkmrk--1"><div class="cm-editor ͼ1 ͼ2 ͼ4 ͼ1q"><button class="cm-copy-button" type="button"><svg height="16" viewbox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path></svg></button></div></div>