By dbx Team on 2024-09-02
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.
The most common format for a Postgres connection string is:
postgresql://[user[:password]@][host][:port][/database][?parameter1=value1&...]
localhost
or an IP address:5432
/mydb
user
password
A complete connection string might look like this:
postgresql://user:password@localhost:5432/mydb
Connection strings can be categorized into two types based on how they handle database connections:
postgresql://user:password@localhost:5432/mydb
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
npm install postgres
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()
Replace the connection string and options with your actual database credentials.
Run the script:
node your-script.js
pip install psycopg2
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)
Replace the connection parameters with your actual database credentials.
Run the script:
python your_script.py
You can add optional parameters to the end of your connection string using ?
followed by key=value
pairs:
sslmode=require
: Force SSL connectionapplication_name=myapp
: Set a name for your application in database logsExample:
postgresql://user:password@localhost:5432/mydb?sslmode=require&application_name=myapp