用java api 实现查询 Hive 数据
版本:cdh5.4.7, hive1.1.0
pom文件
<dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-jdbc</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency>
需要先启动的服务有:
./hive --service hiveserver2
./hive --service metastore
java代码:
public static void main(String[] args) { String connectionURL = "jdbc:hive2://node11:10000/didu"; String drivername = "org.apache.hive.jdbc.HiveDriver"; String username = ""; String password = ""; try { Class.forName(drivername); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } try { Connection con = DriverManager.getConnection(connectionURL, username, password); if(con != null) { System.out.println("Connected"); } else { System.out.println("Not Connected"); } Statement stmt = con.createStatement(); // select * query String sql; ResultSet res; sql = "select * from u_data limit 10"; // sql = "show tables"; System.out.println("Running: " + sql); res = stmt.executeQuery(sql); while (res.next()) { System.out.println(String.valueOf(res.getString(1)) + "\t" + res.getString(2)); } } catch(SQLException se) { se.printStackTrace(); } }
结果展示: