近期在学习HIVE,发现网上的代码都是很早以前的版本,我是使用1.1.1版本的hive。根本没法用,也有很多冲突。不过查阅官网,分析包结构,最后还是弄完了。直接把代码帖上来吧。
package com.yc.hive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
public class HiveUtil {
//网上写 org.apache.hadoop.hive.jdbc.HiveDriver ,新版本不能这样写
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
private static Connection con;
//这里是hive2,网上其他人都写hive,在高版本中会报错
private static String url = "jdbc:hive2://master:10000/default";
private static String user = "hive";
private static String password = "hive";
private static final Logger log = Logger.getLogger(HiveUtil.class);
private static Connection getCon(){
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static ResultSet selectData(String sql,Statement stmt){
ResultSet res=null;
try {
res=stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
public static void loadData(Statement stmt, String sql)
throws SQLException {
//目录 ,我的是hive安装的机子的虚拟机的home目录下
System.out.println("Running:" + sql);
stmt.execute(sql);
}
public static void createTable(Statement stmt,String sql) throws SQLException{
stmt.execute(sql);
}
private static ResultSet showTables(Statement stmt, String tableName) throws SQLException {
String sql = "show tables '" + tableName + "'";
System.out.println("Running:" + sql);
ResultSet res = stmt.executeQuery(sql);
System.out.println("执行 show tables 运行结果:");
return res;
}
private static ResultSet describeTables(Statement stmt, String tableName)
throws SQLException {
String sql = "describe " + tableName;
ResultSet res = stmt.executeQuery(sql);
return res;
}
private static ResultSet selectAll(Statement stmt, String tableName)
throws SQLException {
String sql = "select * from " + tableName;
ResultSet res = stmt.executeQuery(sql);
return res;
}
private static void dropTable(Statement stmt,String tableName) throws SQLException {
// 创建的表名
String sql = "drop table " + tableName;
stmt.execute(sql);
}
public static void main(String[] args) {
try {
String sql="create table newtable (key int, value string) row format delimited fields terminated by '\t'";
con=getCon();
Statement stmt=con.createStatement();
if(!showTables(stmt,"newtable").next()){
createTable(stmt, sql);
}
String sql2="load data local inpath '1' into table newtable";
loadData(stmt, sql2);
ResultSet res=selectAll(stmt,"newtable");
while(res.next()){
System.out.println(res.getString(1)+"\t"+res.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}