Redshift JDBC Program
Steps to connect Redshift database using Java JDBC program
Download the driver from
JDBC 4.1–compatible
driver: https://s3.amazonaws.com/redshift-downloads/drivers/RedshiftJDBC41-1.1.10.1010.jar
The class name for this
driver is
com.amazon.redshift.jdbc41.Driver.
Connect to Eclipse, upload the Redshift JDBC driver using "Build Path" -> Add External Archieves as shown like in below images
The following is the Java class to read data from Redshift table
-----------------------------------------------------------
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcRedshiftConnection {
public static void main(String[] args) {
Connection conn1 = null;
Statement statement = null;
try {
Class.forName("com.amazon.redshift.jdbc41.Driver");
conn1 = DriverManager.getConnection("jdbc:redshift://servername:port/databasename", "username","password");
if (conn1 != null) {
System.out.println("Connected with connection #1");
}
// Create the statement to be used to get the results.
statement = conn1.createStatement();
// Create a query to use.
String query = "select schemaname, tablename from pg_table_def limit 10";
ResultSet resultSet = statement.executeQuery(query);
System.out.println("Printing result...");
while (resultSet.next()) {
String tn = resultSet.getString("schemaname");
String opg = resultSet.getString("tablename");
System.out.println("\t schemaname: " + tn + ", tablename: " + opg );
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn1 != null && !conn1.isClosed()) {
conn1.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
------------------------------------------------------------
Sample output from the above Java Class
Sample output from Redshift Database