Example : Connect to a Cluster by Using Java
The following example connects to a cluster and runs a sample query that returns system tables. It is not
necessary to have data in your database to use this example.
If you are using a server certificate to authenticate your cluster, you can restore the line that uses the
keystore, which is commented out:
props.setProperty("ssl", "true");
For more information about the server certificate, see
Connect to Your Cluster Using SSL (p. 105)
.
For step-by-step instructions to run the following example, see
Running Java Examples for Amazon
Redshift Using Eclipse (p. 118)
.
import java.sql.*;
import java.util.Properties;
public class ConnectToClusterExample {
static final String dbURL = "***jdbc cluster connection string ****"; //e.g.
"jdbc:postgresql://x.y.us-east-1.redshift.amazonaws.com:5439/dev";
static final String MasterUsername = "***master user name***";
static final String MasterUserPassword = "***master user password***";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Dynamically load postgresql driver at runtime.
Class.forName("org.postgresql.Driver");
//Open a connection and define properties.
System.out.println("Connecting to database...");
Properties props = new Properties();
//Uncomment the following line if using a keystore.
//props.setProperty("ssl", "true");
props.setProperty("user", MasterUsername);
props.setProperty("password", MasterUserPassword);
conn = DriverManager.getConnection(dbURL, props);
//Try a simple query.
System.out.println("Listing system tables...");
stmt = conn.createStatement();
String sql;
sql = "select * from information_schema.tables;";
ResultSet rs = stmt.executeQuery(sql);
//Get the data from the result set.
while(rs.next()){
//Retrieve two columns.
String catalog = rs.getString("table_catalog");
String name = rs.getString("table_name");
//Display values.
System.out.print("Catalog: " + catalog);
API Version 2012-12-01
109
Amazon Redshift Management Guide
Connecting to a Cluster by Using Java