最近做项目,有个小问题,JDBC连接hive操作后,由于hive的查询一般都比较久,用beeline或者hive命令行去操作,都可以看到进度信息,但普通的JDBC操作却看不到进度信息。需要获取进度信息,在网上没有找到相关资料后。研究了一下beeline的源代码。其实so easy!!!
package com.bxu.dbTry;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import org.apache.hive.jdbc.HiveStatement;
public class HiveJDBCTest
{
// 驱动程序就是之前在classpath中配置的JDBC的驱动程序的JAR 包中
public static final String DBDRIVER = "org.apache.hive.jdbc.HiveDriver";
// 连接地址是由各个数据库生产商单独提供的,所以需要单独记住
public static final String DBURL = "jdbc:hive2://xxx.xxx.xxx.xxx:10000/default?";
public static void main(String[] args) throws Exception
{
Connection con = null; // 表示数据库的连接对象
Statement stmt = null; // 表示数据库的更新操作
ResultSet result = null; // 表示接收数据库的查询结果
Class.forName(DBDRIVER); // 1、使用CLASS 类加载驱动程序
con = DriverManager.getConnection(DBURL); // 2、连接数据库
System.out.println(con);
stmt = con.createStatement(); // 3、Statement 接口需要通过Connection 接口进行实例化操作
long time = System.currentTimeMillis();
//重点在这个里,启动一个线程,来不断轮询进度信息,进度信息封装在HiveStatement中,因为sql执行的时候executeQuery方法会阻塞。
Thread logThread = new Thread(new LogRunnable((HiveStatement) stmt));
logThread.setDaemon(true);
logThread.start();
result = stmt.executeQuery("select count(x) from xxx.zzzz where ptdate='20170820' ");
while (result.next())
{
String str = result.getString(1);
System.out.println(str);
System.out.println("use time:" + (System.currentTimeMillis() - time));
}
result.close();
con.close(); // 4、关闭数据库
}
//进度信息的轮询线程实现
static class LogRunnable implements Runnable
{
private final HiveStatement hiveStatement;
LogRunnable(HiveStatement hiveStatement)
{
this.hiveStatement = hiveStatement;
}
private void updateQueryLog()
{
try
{
List<String> queryLogs = hiveStatement.getQueryLog();
for (String log : queryLogs)
{
System.out.println("进度信息-->"+log);
}
} catch (Exception e)
{
}
}
@Override
public void run()
{
try
{
while (hiveStatement.hasMoreLogs())
{
updateQueryLog();
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
e.getStackTrace();
}
}
}
}
运行结果:
非常简单的例子,提供大家参考。