0
# Connection Management
1
2
Primary functions and patterns for establishing and managing database connections to PostgreSQL servers using pg8000.
3
4
## Capabilities
5
6
### Primary Connection Function
7
8
Creates a connection to a PostgreSQL database server using the legacy DB-API 2.0 interface.
9
10
```python { .api }
11
def connect(
12
user: str,
13
host: str = "localhost",
14
database: str = None,
15
port: int = 5432,
16
password: str = None,
17
source_address: tuple = None,
18
unix_sock: str = None,
19
ssl_context = None,
20
timeout: float = None,
21
tcp_keepalive: bool = True,
22
application_name: str = None,
23
replication: str = None,
24
startup_params: dict = None,
25
sock = None
26
) -> Connection:
27
"""
28
Create a connection to a PostgreSQL database.
29
30
Parameters:
31
- user: Username for database authentication
32
- host: Database server hostname or IP address
33
- database: Database name to connect to (defaults to username)
34
- port: Database server port number
35
- password: Password for database authentication
36
- source_address: (host, port) tuple for local socket binding
37
- unix_sock: Path to Unix domain socket for local connections
38
- ssl_context: SSL context for encrypted connections
39
- timeout: Socket timeout in seconds
40
- tcp_keepalive: Enable TCP keepalive for connection health
41
- application_name: Application name for connection identification
42
- replication: Replication mode ('database' or 'physical')
43
- startup_params: Additional connection parameters dict
44
- sock: Existing socket connection for database communication
45
46
Returns:
47
Connection object for database operations
48
49
Raises:
50
InterfaceError: Connection parameter or interface errors
51
OperationalError: Database connection errors
52
"""
53
```
54
55
### Module Constants
56
57
Module-level constants defining pg8000's DB-API 2.0 compliance characteristics.
58
59
```python { .api }
60
apilevel: str = "2.0"
61
"""DBAPI level supported by pg8000."""
62
63
threadsafety: int = 1
64
"""Thread safety level - module sharing only, connections not thread-safe."""
65
66
paramstyle: str = "format"
67
"""Parameter style used for SQL queries."""
68
```
69
70
### Connection Examples
71
72
#### Basic Connection
73
74
```python
75
import pg8000
76
77
# Minimal connection
78
conn = pg8000.connect(
79
user="myuser",
80
password="mypassword",
81
database="mydb"
82
)
83
84
# Use connection
85
cursor = conn.cursor()
86
cursor.execute("SELECT current_user")
87
print(cursor.fetchone())
88
89
# Clean up
90
cursor.close()
91
conn.close()
92
```
93
94
#### Advanced Connection Options
95
96
```python
97
import pg8000
98
import ssl
99
100
# Connection with SSL and advanced options
101
ssl_context = ssl.create_default_context()
102
ssl_context.check_hostname = False
103
ssl_context.verify_mode = ssl.CERT_NONE
104
105
conn = pg8000.connect(
106
user="myuser",
107
password="mypassword",
108
host="db.example.com",
109
port=5432,
110
database="production_db",
111
ssl_context=ssl_context,
112
timeout=30.0,
113
tcp_keepalive=True,
114
application_name="MyApp v1.0",
115
startup_params={
116
"search_path": "public,audit",
117
"timezone": "UTC"
118
}
119
)
120
121
# Connection is ready for use
122
cursor = conn.cursor()
123
cursor.execute("SELECT version()")
124
print(cursor.fetchone())
125
126
cursor.close()
127
conn.close()
128
```
129
130
#### Unix Socket Connection
131
132
```python
133
import pg8000
134
135
# Connect using Unix domain socket
136
conn = pg8000.connect(
137
user="myuser",
138
unix_sock="/var/run/postgresql/.s.PGSQL.5432",
139
database="mydb"
140
)
141
142
# Use connection normally
143
cursor = conn.cursor()
144
cursor.execute("SELECT inet_server_addr()")
145
result = cursor.fetchone()
146
print(f"Server address: {result[0]}")
147
148
cursor.close()
149
conn.close()
150
```