Connecting from Code
This section describes how to connect with the JDBC DriverManager or PostgreSQLDataSource interfaces.
Connecting with the DriverManager
When connecting with the DriverManager class, the CData JDBC Driver for PostgreSQL follows the JDBC convention: First, load the PostgreSQL driver class. Then, make a connection.
Load the Driver
The following step is optional per the JDBC 4.0 specification.Class.forName("cdata.jdbc.postgresql.PostgreSQLDriver");
Establish a Connection
Provide the connection string with the getConnection method of the static DriverManager class. Start the connection string with "jdbc:postgresql:". A typical connection string is the following:
Connection conn = DriverManager.getConnection("jdbc:postgresql:User=postgres;Password=admin;Database=postgres;Server=127.0.0.1;Port=5432");Alternatively, you can prepare the connection options using a Properties object. Pass the Properties object to the DriverManager.
Properties prop = new Properties(); prop.setProperty("User","postgres"); prop.setProperty("Password","admin"); prop.setProperty("Database","postgres"); prop.setProperty("Server","127.0.0.1"); prop.setProperty("Port","5432"); Connection conn = DriverManager.getConnection("jdbc:postgresql:",prop);
Connecting with the PostgreSQLDataSource Class
You can use the PostgreSQLDataSource class to create pooled connections, as shown in the following example. See Connection Pooling for more information.
The following example instantiates a pooled Connection object:
PostgreSQLDataSource ds = new PostgreSQLDataSource("jdbc:postgresql:UseConnectionPooling=true;User=postgres;Password=admin;Database=postgres;Server=127.0.0.1;Port=5432");
Connection conn = ds.getConnection();