4. Getting Started With Hive JDBC - 图1

Getting Started With Hive JDBC

How to install JDBC driver

Kyuubi JDBC driver is fully compatible with the 2.3.* version of hive JDBC driver, so we reuse hive JDBC driver to connect to Kyuubi server.

Add repository to your maven configuration file which may reside in $MAVEN_HOME/conf/settings.xml.

  1. <repositories>
  2. <repository>
  3. <id>central maven repo</id>
  4. <name>central maven repo https</name>
  5. <url>https://repo.maven.apache.org/maven2</url>
  6. </repository>
  7. <repositories>

You can add below dependency to your pom.xml file in your application.

  1. <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc -->
  2. <dependency>
  3. <groupId>org.apache.hive</groupId>
  4. <artifactId>hive-jdbc</artifactId>
  5. <version>2.3.7</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.hadoop</groupId>
  9. <artifactId>hadoop-common</artifactId>
  10. <!-- keep consistent with the build hadoop version -->
  11. <version>2.7.4</version>
  12. </dependency>

Use JDBC driver with kerberos

The below java code is using a keytab file to login and connect to Kyuubi server by JDBC.

  1. package org.apache.kyuubi.examples;
  2. import java.io.IOException;
  3. import java.security.PrivilegedExceptionAction;
  4. import java.sql.*;
  5. import org.apache.hadoop.security.UserGroupInformation;
  6. public class JDBCTest {
  7. private static String driverName = "org.apache.hive.jdbc.HiveDriver";
  8. private static String kyuubiJdbcUrl = "jdbc:hive2://localhost:10009/default;";
  9. public static void main(String[] args) throws ClassNotFoundException, SQLException {
  10. String principal = args[0]; // kerberos principal
  11. String keytab = args[1]; // keytab file location
  12. Configuration configuration = new Configuration();
  13. configuration.set(HADOOP_SECURITY_AUTHENTICATION, "kerberos");
  14. UserGroupInformation.setConfiguration(configuration);
  15. UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab);
  16. Class.forName(driverName);
  17. Connection conn = ugi.doAs(new PrivilegedExceptionAction<Connection>(){
  18. public Connection run() throws SQLException {
  19. return DriverManager.getConnection(kyuubiJdbcUrl);
  20. }
  21. });
  22. Statement st = conn.createStatement();
  23. ResultSet res = st.executeQuery("show databases");
  24. while (res.next()) {
  25. System.out.println(res.getString(1));
  26. }
  27. res.close();
  28. st.close();
  29. conn.close();
  30. }
  31. }