Java Code for Running HIVE queries through JDBC

In this article we will see how to run Hive queries through JDBC. We are using apache-hive-1.0.1 and hiveserver2 is running on port 10000 on localhost.

Jars Required

To access Hive through JDBC we need to add the following jars in the classpath:-

guava-18.0.jar
hive-common-1.0.0.jar
hive-exec-0.13.0.jar
hive-jdbc-1.0.0.jar
hive-metastore-1.0.0.jar
hive-serde-1.0.0.jar
hive-service-1.0.0.jar
hive-shims-0.23-1.0.0.jar
hive-shims-1.0.0.jar
hive-shims-common-1.0.0.jar
httpclient-4.2.5.jar
httpcore-4.0.1.jar
libfb303-0.9.0.jar
libthrift-0.9.0.jar

Driver Class

String driverName = "org.apache.hive.jdbc.HiveDriver";

Load Driver Class

Class.forName(driverName);

Get Connection and execute Query

//hive URL-  'jdbc:hive2://<hive server machine>:<hive server port>/<database>'
Connection conn = DriverManager.getConnection("jdbc:hive2://localhost:10000/testdb", "hiveUser", "hivePassword");
Statement stmt = conn.createStatement();

//We will read max salary from table 'Employee' in database 'testdb'
String query = "select max(salary) from Employee";
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
    System.out.println(res.getLong(1));
}

Leave a Reply

Your email address will not be published. Required fields are marked *