Connect via code
This guide provides detailed examples of how to connect your application to a RayDB PostgreSQL cluster using various programming languages.
Connection String Format
Ensure you retrieve your connection string from the RayDB dashboard. The format typically looks like this:
postgres://<user>:<password>@<host>:<port>/<database>?sslmode=requireConnecting with Python (psycopg2)
import psycopg2
connection = psycopg2.connect(
"postgres://user:password@host:port/database?sslmode=require"
)
cursor = connection.cursor()
cursor.execute("SELECT version();")
print(cursor.fetchone())
cursor.close()
connection.close()Connecting with Node.js (pg package)
const { Client } = require('pg');
const client = new Client({
connectionString: 'postgres://user:password@host:port/database?sslmode=require'
});
async function connect() {
await client.connect();
const res = await client.query('SELECT version();');
console.log(res.rows[0]);
await client.end();
}
connect().catch(console.error);Connecting with Go (pgx driver)
package main
import (
"context"
"fmt"
"log"
"github.com/jackc/pgx/v5"
)
func main() {
conn, err := pgx.Connect(context.Background(), "postgres://user:password@host:port/database?sslmode=require")
if err != nil {
log.Fatal("Unable to connect to database:", err)
}
defer conn.Close(context.Background())
var version string
err = conn.QueryRow(context.Background(), "SELECT version();").Scan(&version)
if err != nil {
log.Fatal(err)
}
fmt.Println("PostgreSQL version:", version)
}Best Practices for Secure Connections
- Use Environment Variables: Store credentials in environment variables instead of hardcoding them.
- Connection Pooling: Utilize connection pooling for better performance.
- Error Handling: Implement error handling to manage database connectivity issues.
Refer to the Firewall Configuration guide to ensure proper access control to your cluster.