java 直连hive
时间: 2023-11-29 08:45:34 浏览: 82
以下是Java直连Hive的示例代码:
```java
import java.sql.*;
public class HiveJdbcClient {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://127.0.0.1:10000/test", "test", "test");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.execute("drop table if exists " + tableName); stmt.execute("create table " + tableName + " (key int, value string)");
System.out.println("Table " + tableName + " created.");
// 插入数据
String sql = "insert into " + tableName + " values(1, 'value1'),(2, 'value2')";
stmt.execute(sql);
System.out.println("Insert into " + tableName + " success.");
// 查询数据
sql = "select * from " + tableName;
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(String.valueOf(res.getInt(1)) + "\t" + res.getString(2));
}
stmt.close();
con.close();
}
}
```
这段代码使用JDBC连接Hive,创建了一个名为testHiveDriverTable的表,并向其中插入了两条数据。最后,查询了表中的所有数据并输出到控制台。
阅读全文