2020-07-10 java采用jdbc方式連接hive

如果想要通過(guò)Java進(jìn)行訪問(wèn),首先要在引用一下三個(gè)Jar包:

<dependency>

? ? <groupId>org.apache.hive</groupId>

? ? <artifactId>hive-jdbc</artifactId>

? ? <version>1.0.0</version>

? ? </dependency>

? ? <dependency>

? ? ? ? <groupId>org.apache.hadoop</groupId>

? ? ? ? <artifactId>hadoop-common</artifactId>

? ? ? <version>2.4.1</version>

? ? </dependency>

? ? <dependency>?

<groupId>jdk.tools</groupId>?

<artifactId>jdk.tools</artifactId>

<version>1.8</version>

<scope>system</scope>

<systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>

</dependency>

需要注意的是,包的版本一定要確認(rèn)好,切勿版本過(guò)高 我采用的是CDH5.12.0 版本

如果發(fā)生以下錯(cuò)誤:

?org.apache.thrift.TApplicationException: Required field 'client_protocol' is unset! ? Struct:TOpenSessionReq(client_protocol:null)

則極可能的原因是你項(xiàng)目的hive-jdbc版本和服務(wù)器不一致的原因造成的,替換成和服務(wù)器一致的版本就可以了,

測(cè)試代碼

public static Connection getHiveConnection() {

Connection conn = null;

try {

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

conn = DriverManager.getConnection("jdbc:hive2://cdh-hadoop1:10000/default", "root", "");

} catch (ClassNotFoundException | SQLException e1) {

e1.printStackTrace();

}

return conn;

}

/**

*

* 通過(guò)傳入sql從hive中獲取數(shù)據(jù)

* @param sql

* @return 返回列表信息信息

* @throws SQLException

* @throws ClassNotFoundException

*/

public static List<String> getMessageFromHive(String db, String sql) {

// 這個(gè)方法只有下面兩種操作

// show table partitions

// show create table

List<String> list = new ArrayList<>();

try {

Connection con = getHiveConnection();

Statement stmt = con.createStatement();

? ? //stmt.executeQuery("use "+db);

ResultSet rs = stmt.executeQuery(sql);

while (rs.next()) {

list.add(rs.getString(1));

}

rs.close();

stmt.close();

con.close();

} catch (SQLException e) {

e.printStackTrace();

System.exit(-1);

}

return list;

}

public static void main(String[] args) {

getMessageFromHive("i8ji", "show partitions i8ji.ods_t_db_to_hive_list_arc ");

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容