java JDBC 链接hive 操作实例

来源:互联网 发布:淘宝全球购入口官网 编辑:程序博客网 时间:2024/06/11 00:36

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 stubtry{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) * 1xd * 2xd * 3xd *  * */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));}}}
结果如下:

1xd2xd3xd123btestchoiceclassinoname_classnum //视图名ptestt1testuserinfo



1 0