PostgreSQL JDBC Driver allows Java programs to connect to a PostgreSQL database using standard, database independent Java code.
npx @tessl/cli install tessl/maven-org-postgresql--postgresql@42.7.00
# PostgreSQL JDBC Driver
1
2
The PostgreSQL JDBC Driver (PgJDBC) is the official Java Database Connectivity (JDBC) driver for PostgreSQL. It provides full JDBC 4.2 compliance and extensive PostgreSQL-specific extensions, enabling Java applications to connect to and interact with PostgreSQL databases using standard database-independent Java code while also providing access to PostgreSQL's advanced features.
3
4
## Package Information
5
6
- **Package Name**: org.postgresql:postgresql
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Version**: 42.7.5
10
- **Installation**: Add to Maven `pom.xml`:
11
```xml
12
<dependency>
13
<groupId>org.postgresql</groupId>
14
<artifactId>postgresql</artifactId>
15
<version>42.7.5</version>
16
</dependency>
17
```
18
Or Gradle:
19
```groovy
20
implementation 'org.postgresql:postgresql:42.7.5'
21
```
22
23
## Core Imports
24
25
```java
26
// Main driver class (automatically registered)
27
import org.postgresql.Driver;
28
29
// PostgreSQL-specific connection interface
30
import org.postgresql.PGConnection;
31
32
// DataSource implementations
33
import org.postgresql.ds.PGSimpleDataSource;
34
import org.postgresql.ds.PGConnectionPoolDataSource;
35
import org.postgresql.xa.PGXADataSource;
36
37
// Fastpath API (deprecated)
38
import org.postgresql.fastpath.Fastpath;
39
40
// Standard JDBC interfaces
41
import java.sql.Connection;
42
import java.sql.DriverManager;
43
import java.sql.Statement;
44
import java.sql.PreparedStatement;
45
import java.sql.ResultSet;
46
import java.sql.SQLException;
47
import java.sql.Array;
48
49
// Java utility classes
50
import java.util.Map;
51
52
// XA transaction support (for distributed transactions)
53
import javax.transaction.xa.XAResource;
54
import javax.transaction.xa.Xid;
55
import javax.transaction.xa.XAException;
56
```
57
58
## Basic Usage
59
60
```java
61
import java.sql.Connection;
62
import java.sql.DriverManager;
63
import java.sql.PreparedStatement;
64
import java.sql.ResultSet;
65
import java.sql.SQLException;
66
67
public class BasicExample {
68
public static void main(String[] args) {
69
// Connection URL format: jdbc:postgresql://host:port/database
70
String url = "jdbc:postgresql://localhost:5432/mydb";
71
String user = "postgres";
72
String password = "secret";
73
74
// Connect to database
75
try (Connection conn = DriverManager.getConnection(url, user, password)) {
76
// Execute a query
77
String sql = "SELECT id, name, email FROM users WHERE active = ?";
78
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
79
pstmt.setBoolean(1, true);
80
81
try (ResultSet rs = pstmt.executeQuery()) {
82
while (rs.next()) {
83
int id = rs.getInt("id");
84
String name = rs.getString("name");
85
String email = rs.getString("email");
86
System.out.println(id + ": " + name + " <" + email + ">");
87
}
88
}
89
}
90
} catch (SQLException e) {
91
e.printStackTrace();
92
}
93
}
94
}
95
```
96
97
## Architecture
98
99
The PostgreSQL JDBC Driver is organized around several key architectural components:
100
101
### Core Components
102
103
- **Driver**: The main entry point (`org.postgresql.Driver`) that implements `java.sql.Driver`. Automatically registers with `DriverManager` when the class is loaded.
104
105
- **Connection Management**: Provides both `DriverManager`-based connections and DataSource implementations for pooled/XA scenarios. All connections implement the `PGConnection` interface with PostgreSQL-specific extensions.
106
107
- **Statement Execution**: Full support for `Statement`, `PreparedStatement`, and `CallableStatement` with server-side and client-side prepared statement modes.
108
109
- **Type System**: Comprehensive mapping between Java types and PostgreSQL types, including support for arrays, custom types, geometric types, JSON, and more.
110
111
### Extension APIs
112
113
- **COPY API**: High-performance bulk data transfer using PostgreSQL's COPY protocol
114
- **Large Object API**: Streaming access to large binary objects (BLOBs)
115
- **Replication API**: Support for logical and physical replication streams
116
- **Notification API**: LISTEN/NOTIFY asynchronous messaging
117
118
### Configuration
119
120
The driver supports extensive configuration through:
121
- JDBC URL parameters
122
- Connection properties
123
- DataSource property setters
124
- PostgreSQL environment variables
125
126
## Capabilities
127
128
### Basic Connectivity
129
130
Driver registration, connection URL formats, connection establishment, and connection properties.
131
132
```java { .api }
133
/**
134
* Main JDBC driver class for PostgreSQL
135
*/
136
public class org.postgresql.Driver implements java.sql.Driver {
137
/**
138
* Attempts to make a database connection to the given URL
139
* @param url JDBC URL of the form jdbc:postgresql://host:port/database
140
* @param info Connection properties (user, password, etc.)
141
* @return A Connection object or null if URL is not accepted
142
*/
143
public Connection connect(String url, Properties info) throws SQLException;
144
145
/**
146
* Returns true if the driver can handle the given URL
147
* @param url JDBC URL to check
148
*/
149
public boolean acceptsURL(String url) throws SQLException;
150
151
/**
152
* Manually registers the driver with DriverManager
153
*/
154
public static void register() throws SQLException;
155
156
/**
157
* Deregisters the driver from DriverManager
158
*/
159
public static void deregister() throws SQLException;
160
}
161
```
162
163
[Basic Connectivity](./basic-connectivity.md)
164
165
### DataSource Implementations
166
167
Connection pooling and XA-enabled DataSource implementations for enterprise applications.
168
169
```java { .api }
170
/**
171
* Simple non-pooling DataSource implementation
172
*/
173
public class org.postgresql.ds.PGSimpleDataSource implements DataSource {
174
public Connection getConnection() throws SQLException;
175
public Connection getConnection(String user, String password) throws SQLException;
176
177
public void setServerName(String serverName);
178
public void setPortNumber(int portNumber);
179
public void setDatabaseName(String databaseName);
180
public void setUser(String user);
181
public void setPassword(String password);
182
}
183
184
/**
185
* ConnectionPoolDataSource for use with connection pool managers
186
*/
187
public class org.postgresql.ds.PGConnectionPoolDataSource
188
implements ConnectionPoolDataSource {
189
public PooledConnection getPooledConnection() throws SQLException;
190
public PooledConnection getPooledConnection(String user, String password)
191
throws SQLException;
192
}
193
194
/**
195
* XA-enabled DataSource for distributed transactions
196
*/
197
public class org.postgresql.xa.PGXADataSource implements XADataSource {
198
public XAConnection getXAConnection() throws SQLException;
199
public XAConnection getXAConnection(String user, String password)
200
throws SQLException;
201
}
202
```
203
204
[DataSource Implementations](./datasource.md)
205
206
### Statement Execution
207
208
Executing SQL statements with support for prepared statements, callable statements, and batch operations.
209
210
```java { .api }
211
/**
212
* PostgreSQL-specific extensions to Statement
213
*/
214
public interface org.postgresql.PGStatement extends Statement {
215
/** Represents positive infinity for date/timestamp values */
216
long DATE_POSITIVE_INFINITY = 9223372036825200000L;
217
/** Represents negative infinity for date/timestamp values */
218
long DATE_NEGATIVE_INFINITY = -9223372036832400000L;
219
/** Smaller positive infinity value for compatibility */
220
long DATE_POSITIVE_SMALLER_INFINITY = 185543533774800000L;
221
/** Smaller negative infinity value for compatibility */
222
long DATE_NEGATIVE_SMALLER_INFINITY = -185543533774800000L;
223
224
/**
225
* Returns the OID of the last inserted row
226
*/
227
long getLastOID() throws SQLException;
228
229
/**
230
* Sets the threshold for switching to server-side prepared statements
231
* @param threshold Number of executions before using server prepare (0 = always, negative = never)
232
*/
233
void setPrepareThreshold(int threshold);
234
235
/**
236
* Gets the current prepare threshold
237
*/
238
int getPrepareThreshold();
239
240
/**
241
* Enables or disables adaptive fetch size adjustment
242
*/
243
void setAdaptiveFetch(boolean adaptiveFetch);
244
245
/**
246
* Returns whether adaptive fetch is enabled
247
*/
248
boolean getAdaptiveFetch();
249
}
250
```
251
252
[Statement Execution](./statement-execution.md)
253
254
### ResultSet Handling
255
256
Processing query results with support for scrollable cursors, updateable result sets, and type conversions.
257
258
```java { .api }
259
/**
260
* PostgreSQL-specific ResultSet metadata extensions
261
*/
262
public interface org.postgresql.PGResultSetMetaData extends ResultSetMetaData {
263
/**
264
* Returns the underlying column name (before any aliasing)
265
*/
266
String getBaseColumnName(int column) throws SQLException;
267
268
/**
269
* Returns the underlying table name (before any aliasing)
270
*/
271
String getBaseTableName(int column) throws SQLException;
272
273
/**
274
* Returns the underlying schema name
275
*/
276
String getBaseSchemaName(int column) throws SQLException;
277
278
/**
279
* Returns the format of the column: 0 for text, 1 for binary
280
*/
281
int getFormat(int column) throws SQLException;
282
}
283
```
284
285
[ResultSet Handling](./resultset.md)
286
287
### Transaction Management
288
289
Transaction control with savepoints, isolation levels, and automatic savepoint management.
290
291
```java { .api }
292
/**
293
* Automatic savepoint behavior options
294
*/
295
public enum org.postgresql.jdbc.AutoSave {
296
/** Never use automatic savepoints */
297
NEVER,
298
/** Always create a savepoint before each query */
299
ALWAYS,
300
/** Create savepoints only when needed for error recovery */
301
CONSERVATIVE;
302
303
/**
304
* Returns the string value of this enum (lowercase)
305
* @return Lowercase string representation
306
*/
307
public String value();
308
309
/**
310
* Parses AutoSave from string value
311
* @param value String representation (case-insensitive)
312
* @return AutoSave enum value
313
*/
314
public static AutoSave of(String value);
315
}
316
317
// Transaction methods on PGConnection
318
public interface org.postgresql.PGConnection extends Connection {
319
/**
320
* Gets the current autosave configuration
321
*/
322
AutoSave getAutosave();
323
324
/**
325
* Sets the autosave configuration
326
* @param autoSave Autosave mode
327
*/
328
void setAutosave(AutoSave autoSave);
329
}
330
```
331
332
[Transaction Management](./transactions.md)
333
334
### COPY Operations
335
336
High-performance bulk data transfer using PostgreSQL's COPY protocol.
337
338
```java { .api }
339
/**
340
* Manager for PostgreSQL COPY operations
341
*/
342
public class org.postgresql.copy.CopyManager {
343
/**
344
* Starts a COPY FROM STDIN operation (loading data into database)
345
* @param sql COPY command (e.g., "COPY table FROM STDIN")
346
* @return CopyIn interface for writing data
347
*/
348
public CopyIn copyIn(String sql) throws SQLException;
349
350
/**
351
* Starts a COPY TO STDOUT operation (extracting data from database)
352
* @param sql COPY command (e.g., "COPY table TO STDOUT")
353
* @return CopyOut interface for reading data
354
*/
355
public CopyOut copyOut(String sql) throws SQLException;
356
357
/**
358
* Copies data from a Reader into the database
359
* @param sql COPY command
360
* @param from Reader providing data
361
* @return Number of rows loaded
362
*/
363
public long copyIn(String sql, Reader from) throws SQLException, IOException;
364
365
/**
366
* Copies data from database to a Writer
367
* @param sql COPY command
368
* @param to Writer to receive data
369
* @return Number of rows (for server 8.2+; -1 for older)
370
*/
371
public long copyOut(String sql, Writer to) throws SQLException, IOException;
372
}
373
```
374
375
[COPY Operations](./copy-operations.md)
376
377
### Large Objects
378
379
Streaming access to PostgreSQL Large Objects (LOBs/BLOBs).
380
381
```java { .api }
382
/**
383
* Manager for PostgreSQL Large Objects
384
*/
385
public class org.postgresql.largeobject.LargeObjectManager {
386
/** Mode constant: open for reading */
387
public static final int READ = 0x00040000;
388
/** Mode constant: open for writing */
389
public static final int WRITE = 0x00020000;
390
/** Mode constant: open for reading and writing */
391
public static final int READWRITE = READ | WRITE;
392
393
/**
394
* Creates a new large object (deprecated, use createLO)
395
* @return OID of the created large object
396
* @deprecated As of 8.3, replaced by createLO()
397
*/
398
@Deprecated
399
public int create() throws SQLException;
400
401
/**
402
* Creates a new large object with default READWRITE mode
403
* @return OID of the created large object
404
*/
405
public long createLO() throws SQLException;
406
407
/**
408
* Creates a new large object with specified mode
409
* @param mode Access mode (READ, WRITE, or READWRITE)
410
* @return OID of the created large object
411
*/
412
public long createLO(int mode) throws SQLException;
413
414
/**
415
* Opens an existing large object
416
* @param oid OID of the large object
417
* @param mode Access mode (READ, WRITE, or READWRITE)
418
* @return LargeObject handle for I/O operations
419
*/
420
public LargeObject open(long oid, int mode) throws SQLException;
421
422
/**
423
* Deletes a large object
424
* @param oid OID of the large object to delete
425
*/
426
public void delete(long oid) throws SQLException;
427
}
428
```
429
430
[Large Objects](./large-objects.md)
431
432
### Replication
433
434
Support for PostgreSQL logical and physical replication protocols.
435
436
```java { .api }
437
/**
438
* API for PostgreSQL replication protocol
439
* Available only when connection is opened with replication=database or replication=true
440
*/
441
public interface org.postgresql.replication.PGReplicationConnection {
442
/**
443
* Starts building a replication stream (logical or physical)
444
* @return Fluent builder for configuring replication stream
445
*/
446
ChainedStreamBuilder replicationStream();
447
448
/**
449
* Starts building a create replication slot command
450
* @return Fluent builder for creating replication slot
451
*/
452
ChainedCreateReplicationSlotBuilder createReplicationSlot();
453
454
/**
455
* Drops a replication slot
456
* @param slotName Name of the slot to drop
457
*/
458
void dropReplicationSlot(String slotName) throws SQLException;
459
}
460
```
461
462
[Replication](./replication.md)
463
464
### SSL/TLS Security
465
466
SSL socket factories and configuration for secure connections.
467
468
```java { .api }
469
/**
470
* SSL connection modes
471
*/
472
public enum org.postgresql.jdbc.SslMode {
473
/** Do not use SSL */
474
DISABLE,
475
/** Try non-SSL first, fallback to SSL if server requires it */
476
ALLOW,
477
/** Try SSL first, fallback to non-SSL if server doesn't support it */
478
PREFER,
479
/** Require SSL, but don't verify server certificate */
480
REQUIRE,
481
/** Require SSL and verify server certificate against CA */
482
VERIFY_CA,
483
/** Require SSL and verify server certificate including hostname */
484
VERIFY_FULL;
485
486
/**
487
* Returns whether this mode requires an encrypted connection
488
* @return true if REQUIRE or higher (VERIFY_CA, VERIFY_FULL)
489
*/
490
public boolean requireEncryption();
491
492
/**
493
* Returns whether this mode verifies the server certificate
494
* @return true for VERIFY_CA or VERIFY_FULL
495
*/
496
public boolean verifyCertificate();
497
498
/**
499
* Returns whether this mode verifies the server hostname matches the certificate
500
* @return true only for VERIFY_FULL
501
*/
502
public boolean verifyPeerName();
503
504
/**
505
* Parses SSL mode from connection properties
506
* @param info Connection properties
507
* @return SslMode enum constant
508
* @throws PSQLException if sslmode value is invalid
509
*/
510
public static SslMode of(Properties info) throws PSQLException;
511
}
512
513
/**
514
* Default SSL factory supporting libpq-compatible certificate files
515
* Extends WrappedFactory to provide SSL socket creation
516
*/
517
public class org.postgresql.ssl.LibPQFactory extends WrappedFactory {
518
// Supports ~/.postgresql/ directory for certificates and keys
519
// - root.crt: trusted CA certificates
520
// - postgresql.crt: client certificate
521
// - postgresql.pk8: client private key (PKCS#8 format)
522
}
523
```
524
525
[SSL/TLS Security](./ssl-security.md)
526
527
### PostgreSQL-Specific Types
528
529
Support for PostgreSQL data types including arrays, geometric types, JSON, hstore, and custom types.
530
531
```java { .api }
532
/**
533
* Base class for PostgreSQL custom types
534
*/
535
public class org.postgresql.util.PGobject implements Serializable, Cloneable {
536
/**
537
* Sets the PostgreSQL type name
538
*/
539
public void setType(String type);
540
541
/**
542
* Gets the PostgreSQL type name
543
*/
544
public String getType();
545
546
/**
547
* Sets the value from its string representation
548
*/
549
public void setValue(String value) throws SQLException;
550
551
/**
552
* Gets the string representation of the value
553
*/
554
public String getValue();
555
556
/**
557
* Returns true if value is SQL NULL
558
*/
559
public boolean isNull();
560
}
561
562
// PostgreSQL geometric types
563
public class org.postgresql.geometric.PGpoint extends PGobject {
564
public double x;
565
public double y;
566
567
public PGpoint();
568
public PGpoint(double x, double y);
569
public PGpoint(String value) throws SQLException;
570
}
571
572
public class org.postgresql.geometric.PGbox extends PGobject {
573
public PGpoint[] point; // Array of 2 corner points
574
}
575
576
public class org.postgresql.geometric.PGcircle extends PGobject {
577
public PGpoint center;
578
public double radius;
579
}
580
```
581
582
[PostgreSQL-Specific Types](./postgresql-types.md)
583
584
### Advanced Features
585
586
Notifications (LISTEN/NOTIFY), connection properties, utilities, and specialized features.
587
588
```java { .api }
589
/**
590
* Represents a notification received via LISTEN/NOTIFY
591
*/
592
public interface org.postgresql.PGNotification {
593
/**
594
* Returns the notification channel name
595
*/
596
String getName();
597
598
/**
599
* Returns the process ID of the notifying backend
600
*/
601
int getPID();
602
603
/**
604
* Returns the notification payload (PostgreSQL 9.0+)
605
*/
606
String getParameter();
607
}
608
609
// Notification methods on PGConnection
610
public interface org.postgresql.PGConnection extends Connection {
611
/**
612
* Returns notifications received since last call
613
* @return Array of notifications or null if none
614
*/
615
PGNotification[] getNotifications() throws SQLException;
616
617
/**
618
* Returns notifications with timeout
619
* @param timeoutMillis 0 to block forever, >0 to wait up to specified milliseconds
620
* @return Array of notifications or null if none
621
*/
622
PGNotification[] getNotifications(int timeoutMillis) throws SQLException;
623
624
/**
625
* Returns the backend process ID for this connection
626
*/
627
int getBackendPID();
628
629
/**
630
* Cancels the currently executing query
631
*/
632
void cancelQuery() throws SQLException;
633
634
/**
635
* Escapes an identifier for safe use in SQL
636
*/
637
String escapeIdentifier(String identifier) throws SQLException;
638
639
/**
640
* Escapes a literal string for safe use in SQL
641
*/
642
String escapeLiteral(String literal) throws SQLException;
643
644
/**
645
* Returns the COPY API for the current connection
646
* @return CopyManager for COPY operations
647
*/
648
CopyManager getCopyAPI() throws SQLException;
649
650
/**
651
* Returns the LargeObject API for the current connection
652
* @return LargeObjectManager for large object operations
653
*/
654
LargeObjectManager getLargeObjectAPI() throws SQLException;
655
656
/**
657
* Returns the replication API for the current connection
658
* @return PGReplicationConnection for replication operations
659
*/
660
PGReplicationConnection getReplicationAPI();
661
662
/**
663
* Creates an Array object from the given type name and elements
664
* @param typeName PostgreSQL type name
665
* @param elements Array elements
666
* @return Array object
667
*/
668
Array createArrayOf(String typeName, Object elements) throws SQLException;
669
670
/**
671
* Adds a handler for PostgreSQL custom data types
672
* @param type PostgreSQL type name
673
* @param klass Class implementing PGobject
674
*/
675
void addDataType(String type, Class<? extends PGobject> klass) throws SQLException;
676
677
/**
678
* Adds a handler for PostgreSQL custom data types (deprecated)
679
* @param type PostgreSQL type name
680
* @param className Class name as string
681
* @deprecated As of 8.0, replaced by addDataType(String, Class). This method
682
* does not work correctly for registering classes that cannot be
683
* directly loaded by the JDBC driver's classloader.
684
*/
685
@Deprecated
686
void addDataType(String type, String className);
687
688
/**
689
* Returns the Fastpath API for this connection
690
* @return Fastpath API instance
691
* @throws SQLException if an error occurs
692
* @deprecated This API is somewhat obsolete. Use prepared statements with binary
693
* transmission of parameters for similar performance and greater functionality.
694
*/
695
@Deprecated
696
Fastpath getFastpathAPI() throws SQLException;
697
698
/**
699
* Sets the default statement reuse threshold for server-side prepare
700
* @param threshold Number of executions before using server prepare
701
*/
702
void setPrepareThreshold(int threshold);
703
704
/**
705
* Gets the default statement reuse threshold for server-side prepare
706
* @return Current threshold
707
*/
708
int getPrepareThreshold();
709
710
/**
711
* Sets the default fetch size for statements created from this connection
712
* @param fetchSize Default fetch size
713
*/
714
void setDefaultFetchSize(int fetchSize) throws SQLException;
715
716
/**
717
* Gets the default fetch size for statements created from this connection
718
* @return Current default fetch size
719
*/
720
int getDefaultFetchSize();
721
722
/**
723
* Returns the query execution mode for this connection
724
* @return Current query mode
725
*/
726
PreferQueryMode getPreferQueryMode();
727
728
/**
729
* Changes a user's password to the specified new password
730
* @param user Username of the database user
731
* @param newPassword New password (array will be zeroed after use)
732
* @param encryptionType Encryption type (null, "md5", or "scram-sha-256")
733
*/
734
void alterUserPassword(String user, char[] newPassword, String encryptionType) throws SQLException;
735
736
/**
737
* Returns current values of all parameters reported by the server
738
* @return Unmodifiable map of parameter names to values
739
*/
740
Map<String, String> getParameterStatuses();
741
742
/**
743
* Returns the value of a specific server parameter
744
* @param parameterName Parameter name (case-insensitive)
745
* @return Parameter value or null if not defined
746
*/
747
String getParameterStatus(String parameterName);
748
749
/**
750
* Enables or disables adaptive fetch for connection
751
* @param adaptiveFetch Desired state of adaptive fetch
752
*/
753
void setAdaptiveFetch(boolean adaptiveFetch);
754
755
/**
756
* Returns the state of adaptive fetch for connection
757
* @return True if adaptive fetch is enabled
758
*/
759
boolean getAdaptiveFetch();
760
}
761
```
762
763
[Advanced Features](./advanced-features.md)
764
765
## Connection Properties
766
767
The driver supports extensive configuration through connection properties. Key properties include:
768
769
- **user**: Database username
770
- **password**: Database password
771
- **ssl**: Enable SSL (true/false)
772
- **sslmode**: SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
773
- **prepareThreshold**: Threshold for server-side prepared statements (default: 5)
774
- **defaultRowFetchSize**: Default fetch size for ResultSets (default: 0 = all rows)
775
- **loginTimeout**: Login timeout in seconds
776
- **connectTimeout**: Connection timeout in seconds
777
- **socketTimeout**: Socket timeout in seconds
778
- **ApplicationName**: Application name for connection tracking
779
- **replication**: Enable replication protocol (database, true)
780
- **assumeMinServerVersion**: Assume minimum PostgreSQL version to skip version checks
781
- **binaryTransfer**: Enable binary transfer for better performance (default: true)
782
- **autosave**: Automatic savepoint mode (never, always, conservative)
783
- **preferQueryMode**: Query execution mode (simple, extended, extendedForPrepared, extendedCacheEverything)
784
785
Properties can be set in the JDBC URL, Properties object, or via DataSource setters:
786
787
```java
788
// In URL
789
String url = "jdbc:postgresql://localhost/db?user=postgres&ssl=true&sslmode=require";
790
791
// In Properties
792
Properties props = new Properties();
793
props.setProperty("user", "postgres");
794
props.setProperty("password", "secret");
795
props.setProperty("ssl", "true");
796
props.setProperty("sslmode", "require");
797
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/db", props);
798
799
// Via DataSource
800
PGSimpleDataSource ds = new PGSimpleDataSource();
801
ds.setServerName("localhost");
802
ds.setDatabaseName("db");
803
ds.setUser("postgres");
804
ds.setPassword("secret");
805
ds.setSsl(true);
806
ds.setSslMode("require");
807
Connection conn = ds.getConnection();
808
```
809
810
## Exception Handling
811
812
PostgreSQL-specific exceptions provide detailed error information:
813
814
```java { .api }
815
/**
816
* PostgreSQL-specific SQLException with server error details
817
*/
818
public class org.postgresql.util.PSQLException extends SQLException {
819
/**
820
* Returns detailed server error message with additional context
821
*/
822
public ServerErrorMessage getServerErrorMessage();
823
}
824
825
/**
826
* Detailed error/warning message from PostgreSQL server
827
*/
828
public class org.postgresql.util.ServerErrorMessage implements Serializable {
829
public String getSeverity();
830
public String getSQLState();
831
public String getMessage();
832
public String getDetail();
833
public String getHint();
834
public int getPosition();
835
public String getWhere();
836
public String getSchema();
837
public String getTable();
838
public String getColumn();
839
public String getDatatype();
840
public String getConstraint();
841
public String getFile();
842
public int getLine();
843
public String getRoutine();
844
public String getInternalQuery();
845
public int getInternalPosition();
846
}
847
```
848
849
## Type Mappings
850
851
Standard JDBC type mappings plus PostgreSQL-specific types:
852
853
| PostgreSQL Type | Java Type | JDBC Type |
854
|----------------|-----------|-----------|
855
| boolean | boolean | BIT |
856
| smallint | short | SMALLINT |
857
| integer | int | INTEGER |
858
| bigint | long | BIGINT |
859
| real | float | REAL |
860
| double precision | double | DOUBLE |
861
| numeric, decimal | java.math.BigDecimal | NUMERIC |
862
| character, varchar, text | String | VARCHAR |
863
| bytea | byte[] | BINARY |
864
| date | java.sql.Date | DATE |
865
| time | java.sql.Time | TIME |
866
| timestamp | java.sql.Timestamp | TIMESTAMP |
867
| json, jsonb | org.postgresql.util.PGobject | OTHER |
868
| uuid | java.util.UUID | OTHER |
869
| array types | java.sql.Array | ARRAY |
870
| hstore | java.util.Map | OTHER |
871
| geometric types | org.postgresql.geometric.* | OTHER |
872
873
## Multi-Host Connections
874
875
The driver supports multiple hosts for high availability and load balancing:
876
877
```java
878
// Multiple hosts with automatic failover
879
String url = "jdbc:postgresql://host1:5432,host2:5432,host3:5432/database"
880
+ "?targetServerType=primary&loadBalanceHosts=true";
881
```
882
883
Properties:
884
- **targetServerType**: any, primary, secondary, preferSecondary
885
- **loadBalanceHosts**: Enable random host selection (true/false)
886
- **hostRecheckSeconds**: Time between host status rechecks
887
888
## Performance Considerations
889
890
- **Prepared Statements**: Use `PreparedStatement` for repeated queries. Set `prepareThreshold` to control when server-side prepare is used.
891
- **Batch Operations**: Use `addBatch()` and `executeBatch()` for bulk inserts/updates.
892
- **Fetch Size**: Set fetch size on statements to control memory usage for large result sets.
893
- **Binary Transfer**: Keep `binaryTransfer=true` (default) for better performance.
894
- **Connection Pooling**: Use external pooling (HikariCP, Apache DBCP) rather than built-in pooling.
895
- **COPY Protocol**: Use `CopyManager` for bulk data loading/unloading (much faster than INSERT).
896