Hive的Java客户端操作分为JDBC和Thrifit Client,首先启动Hive远程服务:
hive --service hiveserver
一、JDBC
在MyEclipse中首先创建连接
import java.sql.DriverManager; import java.sql.SQLException; public class JDBCUtils { private static String driver="org.apache.hadoop.hive.jdbc.HiveDrive"; private static String url="jdbc:hive://192.168.133.100:10000/default"; //注册驱动 static{ try{ Class.forName(driver); }catch(ClassNotFoundException e){ throw new ExceptionInInitializerError(e); } } //获取连接 public static Connection getConnection(){ try{ return DriverManager.getConnection(url); }catch(SQLException e){ e.printStackTrace(); } return null; } //释放资源 public static void release(Connection conn,Statement st,ResultSet rs){ if(conn!=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); }finally{ conn=null; } } if(st!=null){ try{ st.close(); }catch(SQLException e){ e.printStackTrace(); }finally{ st=null; } } if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); }finally{ rs=null; } } } }
然后执行HQL
public class HIveJDBCDemo { public static void main(String[] args){ Connection conn=null; Statement st=null; ResultSet rs=null; String sql ="select * from test"; try{ //获取连接 conn=JDBCUtils.getConnection(); //创建运行环境 st=conn.createStatement(); //运行HQL rs=st.executeQuery(sql); //处理数据 while(rs.next()){ String name=rs.getString("name"); System.out.println(name); } }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.release(conn,st,rs); } } }
二、Thrifit Client