9951 explained code solutions for 126 technologies


amazon-redshiftHow do I connect to Amazon Redshift using JDBC?


  1. Download the Amazon Redshift JDBC driver from the Amazon Redshift JDBC driver download page
  2. Add the driver to your classpath.
  3. Create a JDBC connection URL using the following syntax:
jdbc:redshift://<hostname>:<port>/<dbname>

where <hostname> is the endpoint of your cluster, <port> is the port your cluster is using, and <dbname> is the name of your database.

  1. Establish a connection using the DriverManager.getConnection() method, passing in the connection URL, username, and password as parameters.
String url = "jdbc:redshift://examplecluster.1234567890.us-west-2.redshift.amazonaws.com:5439/dev";
String user = "awsuser";
String password = "mypassword";

Connection con = DriverManager.getConnection(url, user, password);
  1. Once the connection is established, you can execute SQL statements using the Statement or PreparedStatement interfaces.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
    System.out.println(rs.getString("column1"));
}
  1. When you are finished, close the connection using the Connection.close() method.
con.close();
  1. For more information, refer to the Amazon Redshift JDBC Driver Developer Guide.

Edit this code on GitHub