java JDBC 链接hive 操作实例
- - CSDN博客云计算推荐文章1.在eclipse下面 导入包,简便方式 new ->mapred project -> 右键 ->选择“Properties”->Java Build Path->Library->Add External Jars 将/usr/hive/lib的所有jar包 添加上. (因为之前的配置 所有jar包 已经包括 java链接mysql的包).
1.在eclipse下面 导入包,简便方式 new ->mapred project -> 右键 ->选择“Properties”->Java Build Path->Library->Add External Jars 将/usr/hive/lib的所有jar包 添加上。(因为之前的配置 所有jar包 已经包括 java链接mysql的包)。
2. 开启服务接口:
hive --service hiveserver >/dev/null 2>/dev/null &
或者:hive --service hiveservice
3. 编写测试代码:
package hive; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class hiveTest { /** * @XD */ private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; private static String sql = ""; private static ResultSet res; public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub try{ Class.forName(driverName); }catch(ClassNotFoundException e){ e.printStackTrace(); System.exit(1); } Connection conn = DriverManager.getConnection("jdbc:hive://localhost:10000/default", "", ""); Statement stmt = conn.createStatement(); //创建的表名 String tablename = "test"; //stmt.executeQuery(sql)和res = stmt.executeQuery(sql); 成对出现 一面出错 /** * Tips :sql语句的 注意事项 和hive shell 里面的一致 * sql = " drop table " 注意空格的要求 不能紧挨着书写 会出现错误 * * */ sql = " drop table "+tablename; stmt.executeQuery(sql); res = stmt.executeQuery(sql); sql = " create table "+tablename+"(key int,value string)"; sql += "row format delimited fields terminated by '\t'"; res = stmt.executeQuery(sql); /** * test.txt:(分隔符\t) * 1 xd * 2 xd * 3 xd * * */ String filepath = "/home/hadoop/桌面/test.txt"; sql = " load data local inpath '"+filepath+"' overwrite into table "+tablename; stmt.executeQuery(sql); res = stmt.executeQuery(sql); sql = "select * from "+tablename ; res = stmt.executeQuery(sql); while(res.next()){ System.out.println(res.getInt(1)+"\t"+res.getString(2)); } sql = "select * from userinfo" ; res = stmt.executeQuery(sql); while(res.next()){ System.out.println(res.getString(1)); } //虽然hive创建视图的时候 在hive数据仓库目里显示不出来 但是api链接的是hive数据库 可以将视图显示出来 sql = "show tables"; res = stmt.executeQuery(sql); while(res.next()){ System.out.println(res.getString(1)); } } }结果如下:
1 xd 2 xd 3 xd 1 2 3 btest choice classino name_classnum //视图名 ptest t1 test userinfo