import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HiveUtil {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public Connection getConnection() throws SQLException,
ClassNotFoundException {
Class.forName(driverName);
Connection con = DriverManager.getConnection(
"jdbc:hive://localhost:10000/default", "", "");
return con;
}
public void execute(String exeStr) throws ClassNotFoundException,
SQLException {
Connection con = getConnection();
Statement stmt = con.createStatement();
stmt.execute(exeStr);
con.close();
stmt.close();
}
public ResultSet executeQuery(String queryStr)
throws ClassNotFoundException, SQLException {
Connection con = getConnection();
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(queryStr);
try {
if (res.next()) {
return res;
} else {
return null;
}
} catch (Exception e) {
// TODO: handle exception
return null;
} finally {
con.close();
stmt.close();
}
}
public static void main(String[] args) throws Exception {
Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
String dropSQL = "drop table javabloger";
String createSQL = "create table javabloger (key int, value string)";
// hive插入数据支持两种方式一种:load文件,令一种为从另一个表中查询进行插入(感觉这是个鸡肋)
// hive是不支持insert into...values(....)这种操作的
String insterSQL = "LOAD DATA LOCAL INPATH '/APP/nnn/hiveTable.txt' OVERWRITE INTO TABLE javabloger";
String querySQL = "SELECT a.* FROM javabloger a";
Connection con = DriverManager.getConnection(
"jdbc:hive://192.*******:10000/default", "", "");
Statement stmt = con.createStatement();
stmt.execute(dropSQL); // 执行删除语句
stmt.execute(createSQL); // 执行建表语句
stmt.execute(insterSQL); // 执行插入语句
ResultSet res = stmt.executeQuery(querySQL); // 执行查询语句
while (res.next()) {
System.out.println("Result: key:" + res.getString(1)
+ " –> value:" + res.getString(2));
}
}
}
所用到的jar包:
antlr-runtime-3.0.1.jar
hive-exec-0.7.1.jar
hive-jdbc-0.7.1.jar
hive-metastore-0.7.1.jar
hive-service-0.7.1.jar
jdo2-api-2.3-ec.jar
libfb303.jar
可以通过Eclipse在windows上调试,远程调用linux上的hive,程序中load的文件也是远程linux上的文件‘并非windows上的文件