User guide

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 Configure Security Options for Connections (p. 158).
For step-by-step instructions to run the following example, see Running Java Examples for Amazon
Redshift Using Eclipse (p. 130).
package connection;
import java.sql.*;
import java.util.Properties;
public class Docs {
//Redshift driver: "jdbc:redshift://x.y.us-west-2.redshift.amazon
aws.com:5439/dev";
//or "jdbc:postgresql://x.y.us-west-2.redshift.amazonaws.com:5439/dev";
static final String dbURL = "***jdbc cluster connection string ****";
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 driver at runtime.
//Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver
//Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver
Class.forName("com.amazon.redshift.jdbc4.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()){
API Version 2012-12-01
170
Amazon Redshift Management Guide
Connecting to Clusters From Client Tools and Code