Java HIVE 使用Jdbc连接Hive

谁借莪1个温暖的怀抱¢ 2022-03-18 13:28 410阅读 0赞

1,使用Jdbc方式链接hive,首先需要启动hive的Thrift Server,否则会导致错误

hive —service hiveserver 是两”-“,

Could not establish connection to localhost:10000/default: java.net.ConnectException: Connection refused

2,简单的Java代码实现;

——通过Class.forName(“org.apache.hadoop.hive.jdbc.HiveDriver”);加载hive驱动

——通过Connection conn = DriverManager.getConnection(“jdbc:hive://localhost:10000/default”,””,””);建立与数据库的连接

eg:

package hive.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class HiveJdbcDriver {

  1. public static void main(String\[\] args) throws Exception \{
  2. Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
  3. Connection conn = DriverManager.getConnection("jdbc:hive://localhost:1000/default","","");
  4. Statement stmt = conn.createStatement();
  5. String tablename = "u\_data\_new";
  6. String quary\_sql = "select weekday,count(\*) from " + tablename + " group by weekday";
  7. ResultSet rs = stmt.executeQuery(quary\_sql);
  8. while(rs.next())\{
  9. System.out.println("weekday: "+rs.getInt(1)+"count: "+rs.getInt(2));
  10. \}
  11. \}

}

result:

weekday: 2 count: 13579
weekday: 3 count: 14430
weekday: 4 count: 15114
weekday: 5 count: 14743
weekday: 6 count: 18229
weekday: 7 count: 11651

hive执行结果:

hive> select weekday,count(*) from u_data_new group by weekday;
1365593910_7419.png

发表评论

表情:
评论列表 (有 0 条评论,410人围观)

还没有评论,来说两句吧...

相关阅读