Tuesday, June 14, 2016

Redshift JDBC Program

Redshift JDBC Program

Steps to connect Redshift database using Java JDBC program

Download the driver from
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


7 comments:


  1. I found some useful information in your blog, it was awesome to read, thanks for sharing

    RedShift Training
    AWS RedShift Training
    Amazon RedShift Online Training

    ReplyDelete
  2. If you're responsible for overseeing an entire organization's data management, you're doing more than just keeping the lights on. You're looking at the long term and laying the groundwork for your organization's data strategy. That strategy might includedata warehousing which is a practice of collecting, cleansing, and organizing data from disparate sources for central storage and analysis.

    ReplyDelete