dbx

Understanding PostgreSQL Connection Strings

By dbx Team on 2024-09-02

What is a Connection String?

A connection string is a compact way to specify all the parameters needed to connect to a PostgreSQL database. It's a single line of text that includes details like the host, port, database name, username, and password.

What Is The Basic Format For A Postgres Connection String?

The most common format for a Postgres connection string is:

postgresql://[user[:password]@][host][:port][/database][?parameter1=value1&...]

What Are The Essential Components of a Postgres Connection String?

  1. Host: The server where your database is located
    • Example: localhost or an IP address
  2. Port: The network port for the database (default is 5432)
    • Example: :5432
  3. Database: The name of the specific database you're connecting to
    • Example: /mydb
  4. Username: Your database user account
    • Example: user
  5. Password: Your database user password
    • Example: password

Putting It All Together

A complete connection string might look like this:

postgresql://user:password@localhost:5432/mydb

Pooling vs Non-Pooling URLs

Pooling vs Non-Pooling URLs

Connection strings can be categorized into two types based on how they handle database connections:

Non-Pooling URLs

  • Establish a new connection for each database operation
  • Typically used in simple applications or scripts
  • Example: postgresql://user:password@localhost:5432/mydb

Pooling URLs

  • Maintain a pool of reusable connections

  • Improve performance in high-concurrency scenarios

  • Often indicated by a different prefix or additional parameters

  • Example: postgresql+pool://user:password@localhost:5432/mydb

How To Connect To A Postgres Database Using JavaScript/TypeScript

  1. Install the "postgres" npm package:
npm install postgres
  1. Create a new JavaScript or TypeScript file and add the following code:
import postgres from 'postgres'

const sql = postgres('postgres://username:password@host:port/database', {
  host: 'localhost',
  port: 5432,
  database: 'database_name',
  username: 'database_user',
  password: 'user_password',
  ssl: false,
  max: 10,
})

async function getUserById(id) {
  const result = await sql`
    SELECT * FROM users WHERE id = ${id}
  `
  return result[0]
}

async function main() {
  try {
    const user = await getUserById(1)
    console.log(user)
  } catch (error) {
    console.error('Error fetching user:', error)
  } finally {
    await sql.end()
  }
}

main()
  1. Replace the connection string and options with your actual database credentials.

  2. Run the script:

node your-script.js

How To Connect To A Postgres Database Using Python

  1. Install the psycopg2 library:
pip install psycopg2
  1. Create a new Python file and add the following code:
import psycopg2
from psycopg2.extras import RealDictCursor

params = {
    "host": "localhost",
    "database": "database_name",
    "user": "database_user",
    "password": "user_password",
    "port": 5432
}

def get_user_by_id(user_id):
    conn = None
    try:
        conn = psycopg2.connect(**params)
        cur = conn.cursor(cursor_factory=RealDictCursor)
        cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
        return cur.fetchone()
    except (Exception, psycopg2.Error) as error:
        print("Error connecting to PostgreSQL database:", error)
    finally:
        if conn:
            cur.close()
            conn.close()

user = get_user_by_id(1)
print(user)
  1. Replace the connection parameters with your actual database credentials.

  2. Run the script:

python your_script.py

Optional Parameters

You can add optional parameters to the end of your connection string using ? followed by key=value pairs:

  • sslmode=require: Force SSL connection
  • application_name=myapp: Set a name for your application in database logs

Example:

postgresql://user:password@localhost:5432/mydb?sslmode=require&application_name=myapp

Best Practices

  1. Security: Avoid putting passwords directly in connection strings, especially in code repositories
  2. Environment Variables: Use environment variables to store sensitive information
  3. URL Encoding: Special characters in usernames or passwords should be URL encoded
  4. Connection Pooling: Use connection pooling for better performance in high-traffic applications
  5. Load Balancing: For AWS RDS users, utilize both writer and reader endpoints appropriately

Troubleshooting Tips

  • Double-check host and port settings
  • Ensure the database name is correct
  • Verify your username and password
  • Check firewall settings if connecting to a remote database
  • For AWS RDS users, make sure you're using the correct endpoint (writer/reader) for your operation type