fesh个人实践,欢迎经验交流!本文Blog地址:http://www.cnblogs.com/fesh/p/3877740.html
完成《在Hadoop-2.2.0集群上安装 Hive-0.13.1 with MySQL》后,这里具体介绍JDBC接口,如果是以集群中的节点作为客户端来访问Hive,则可以直接使用 jdbc:hive:// 。对于一个非集群节点的客户端来说,可以使用 jdbc:hive://host:port/dbname 来进行访问。为了方便用户的使用,这里介绍如何使用Eclipse进行程序的开发。
一、开启HiveServer
开启Hive监听用户的链接
./bin/hive --service hiveserver &
二、On Eclipse
新建Java项目,通过引入外部包添加Hive依赖包(Hive JAR包、日志JAR包、Hadoop JAR包)
使用Java编写的JDBC客户端访问Hive的代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");// DriverName 注册Hive驱动 //建立与Hive数据库的连接, 默认端口10000,使用数据库:hive,用户名密码:hive Connection conn = DriverManager.getConnection( "jdbc:hive://192.168.163.130:10000/hive", "hive", "hive");// URL,USER,PASSWORD Statement stmt = conn.createStatement(); String tableName = "test";// 表名 String sql = "DROP TABLE " + tableName;// 如果已经存在就删除 stmt.executeQuery(sql); sql = "CREATE TABLE " + tableName + " (userID INT,movieID INT,rating INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'"; stmt.executeQuery(sql); // 执行“LOAD DATA INTO TABLE”操作 String filepath = "/home/fesh/workspace/HiveClient/testhive.txt"; sql = "LOAD DATA LOCAL INPATH '" + filepath + "' OVERWRITE INTO TABLE " + tableName; stmt.executeQuery(sql); System.out.println(sql); // 执行“SELCET”操作 sql = "SELECT * FROM " + tableName; System.out.println(sql); ResultSet res = stmt.executeQuery(sql); System.out.println("SELCET运行结果:"); while (res.next()) { System.out.println(res.getInt(1) + "\t" + res.getString(2)+ "\t" + res.getString(3)); } conn.close(); conn = null; } }
得到结果
LOAD DATA LOCAL INPATH '/home/fesh/workspace/HiveClient/testhive.txt' OVERWRITE INTO TABLE test SELECT * FROM test SELCET运行结果: 1 1 3 1 2 4 1 3 5
在HDFS中查看
参考:
1、https://cwiki.apache.org/confluence/display/Hive/HiveClient