Hive connection using java

Here is a sample java code to connect hive database through JDBC.

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class HiveJdbcTest{
  private static String driverName = "org.apache.hive.jdbc.HiveDriver";

  public static void main(String[] args) throws SQLException {
    try {
      Class.forName(driverName);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }

    Connection con = DriverManager.getConnection("jdbc:hive2://<hive_server>:10000/<db>", "", "");
    Statement stmt = con.createStatement();
    String sql = "show tables";
    System.out.println("Current query: " + sql);
    ResultSet res = stmt.executeQuery(sql);
    if (res.next()) {
      System.out.println(res.getString(1));
        }

  }
}

If you are facing any trouble compiling or running this program include hive and hadoop libraries to classpath using :

export CLASSPATH=.:/usr/lib/hive/lib/*:/usr/lib/hadoop/client-0.20/*

If any of the libraries(jars) doesn’t exist on your server, copy these libraries from the server where hadoop is installed.

We are ready to compile and run the program

javac HiveJdbcTest.java
java  HiveJdbcTest

Good Luck !!

Leave a Reply

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