使用 JDBC 连接 Hive(ClassNotFoundException、No suitable driver found、Could not open client transport wit)

package hive;

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

public class App {
    public static void main(String[] args) throws Exception {

        Class.forName("org.apache.hive.jdbc.HiveDriver");
        Connection conn = DriverManager.getConnection("jdbc:hive2://hadoop0:10000/default", "", "");
                                                // default 为 hive的数据库名
        Statement stmt = conn.createStatement();
        String querySQL="SELECT * FROM default.t1";

        ResultSet res = stmt.executeQuery(querySQL);  

        while (res.next()) {
        System.out.println(res.getInt(1));
        }
    }
}

连接时的三大问题

JDBC 连接 Hive 时可能会出现的问题,主要是因为 hive 版本的区别;

  • (1)java.lang.ClassNotFoundException: org.apache.hadoop.hive.jdbc.HiveDriver

    解决方案:

    Class.forName("org.apache.hive.jdbc.HiveDriver");

    而不是:

    Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
  • (2)java.sql.SQLException: No suitable driver found for jdbc:hive://localhost:10000/default

    在 hive 1.2.1 需要 jdbc:hive2://localhost:10000/default 而不是 jdbc:hive://localhost:10000/default

  • (3)java.sql.SQLException: Could not open client transport with JDBC Uri: jdbc:hive2://X.X.X.X:10000/default: java.net.ConnectException: Connection refused

    对于 hive 1.2 及以上的版本,hive不再使用,而直接使用 hiveserver2 命令;

    在Linux shell:

    [root@hadoop0 ~]# hiveserver2 &

References

[1] Connect from Java to Hive using JDBC

[2] java.sql.SQLException: No suitable driver found for jdbc:hive://localhost:10000/default

[3] How to start hiveserver2 as service

你可能感兴趣的:(使用 JDBC 连接 Hive(ClassNotFoundException、No suitable driver found、Could not open client transport wit))