Skip to content

Instantly share code, notes, and snippets.

@nagataka
Created April 12, 2017 06:53
Show Gist options
  • Save nagataka/2c2d9fa49b03e8556faf85345b43f59c to your computer and use it in GitHub Desktop.
Save nagataka/2c2d9fa49b03e8556faf85345b43f59c to your computer and use it in GitHub Desktop.
Connect to Presto on EMR via JDBC
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class PrestoJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.facebook.presto.jdbc.PrestoDriver";
//static final String JDBC_DRIVER = "com.teradata.presto.jdbc42.Driver";
static final String DB_URL = "jdbc:presto://ec2-xx-xx-xxx-xxx.ap-northeast-1.compute.amazonaws.com:8889/hive/default";
// Database credentials
static final String USER = "hadoop";
static final String PASS = "";
public static void main(String[] args) throws URISyntaxException {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
//conn = DriverManager.getConnection(DB_URL,USER,PASS);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
stmt = conn.createStatement();
String sql;
sql = "select * from sales";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
/*
//Retrieve by column name
int nationkey = rs.getInt("n_nationkey");
String name = rs.getString("n_name");
int regionkey = rs.getInt("n_regionkey");
String comment = rs.getString("n_comment");
*/
//Display values
System.out.println(rs.getString(1));
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment