本文主要向大家介绍hive2.0的jdbc程序开发。
前提条件
hive的hiveserver2可正常工作。
验证方法
- 进入hive的bin目录执行./hiveserver2命令
- 通过客户机使用telnet hive_ip 10000命令检查hiveserver2是否可进行连接。
开发环境
- hive2.0.0+hadoop2.7.1
- JDK1.7
- maven2
maven pom.xml文件dependency配置如下
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.1</version>
</dependency>
程序代码如下:
package com.hivelearn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class HiveTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
testHive();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void testHive() throws SQLException, ClassNotFoundException{
Connection conn = null;
Statement stmt= null;
ResultSet res= null;
try {
/*1注册驱动*/
Class.forName("org.apache.hive.jdbc.HiveDriver");
/*2建立连接*/
conn = DriverManager.getConnection("jdbc:hive2://192.168.1.120:10000", "hadoop", "hadoop");
/*3创建语句对象*/
stmt = conn.createStatement();
/*4执行查询语句*/
res = stmt.executeQuery("SELECT count(*) as rs,sex FROM student group by sex");
/*5通过结果集元数据获取列信息 start*/
ResultSetMetaData resmd = res.getMetaData();
for (int i=0; i<resmd.getColumnCount(); i++){
System.out.print(resmd.getColumnName(i+1)+"\t");
}
System.out.println();
/*6输出结果*/
while(res.next()){
for (int i=0; i<resmd.getColumnCount(); i++){
System.out.print(res.getString(resmd.getColumnName(i+1))+"\t");
}
System.out.println();
}
} finally{
try{
if(res!=null){
res.close();
}
} catch(SQLException ex){
throw ex;
}
try{
if(stmt!=null){
stmt.close();
}
} catch(SQLException ex){
throw ex;
}
try{
if(conn!=null){
conn.close();
}
} catch(SQLException ex){
throw ex;
}
}
}
}