启动远程客户端 # hive --service hiveserver2
获取连接-〉创建运行环境-〉执行HQL-〉处理结果-〉释放资源
工具类
1 package demo.utils; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 10 public class JDBCUtils { 11 private static String driverString = "org.apache.hive.jdbc.HiveDriver"; 12 private static String urlString = "jdbc:hive2://sd-9c1f-2eac:10000/default"; 13 static { 14 try { 15 Class.forName(driverString); 16 } catch (ClassNotFoundException e) { 17 throw new ExceptionInInitializerError(e); 18 } 19 } 20 21 22 public static Connection getConnection() { 23 try { 24 return DriverManager.getConnection(urlString); 25 } catch (SQLException e) { 26 e.printStackTrace(); 27 } 28 return null; 29 } 30 31 public static void release (Connection conn, Statement st, ResultSet rs){ 32 if (rs!=null){ 33 try{ 34 rs.close(); 35 }catch(SQLException e){ 36 e.printStackTrace(); 37 }finally{ 38 rs=null; 39 } 40 } 41 if (st!=null){ 42 try{ 43 st.close(); 44 }catch(SQLException e){ 45 e.printStackTrace(); 46 }finally{ 47 st=null; 48 } 49 } 50 if (conn!=null){ 51 try{ 52 conn.close(); 53 }catch(SQLException e){ 54 e.printStackTrace(); 55 }finally{ 56 conn=null; 57 } 58 } 59 } 60 61 }
测试类
1 package demo.hive; 2 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 import demo.utils.JDBCUtils; 9 10 public class HiveJDBCDemo { 11 public static void main(String[] args) { 12 Connection conn=null; 13 Statement st=null; 14 ResultSet rs=null; 15 String sql="select * from sampledata"; 16 conn=JDBCUtils.getConnection(); 17 try { 18 st=conn.createStatement(); 19 rs = st.executeQuery(sql); 20 while(rs.next()){ 21 String sid = rs.getString(1); 22 String sname = rs.getString(2); 23 String gender = rs.getString(3); 24 System.out.println(sid+" "+sname+" "+gender); 25 } 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 }finally{ 29 JDBCUtils.release(conn, st, rs); 30 } 31 32 } 33 34 35 }
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/PL62716/workspace/HiveDemo/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/PL62716/workspace/HiveDemo/lib/slf4j-log4j12-1.7.22.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory] ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. 1 Tom M 2 Mary F 3 Jerry M 4 Rose M 5 Mike F
add hive/lib->all jar and hadoop->share->hadoop->common->hadoop-common.jar to project build path.