You need to enable JavaScript to run this app.
导航

Hive 连接方式

最近更新时间2023.10.17 17:24:49

首次发布时间2022.09.22 16:55:45

本文为您介绍在 E-MapReduce 集群提交 Hive SQL 的三种方式。

1 前提条件

  1. 使用 SSH 方式登录到集群主节点,详情请参见使用 SSH连接主节点

2 连接方式

2.1 方式一:通过 hive 客户端

  1. 执行以下命令,切换为 hive 用户。
su hive
  1. 执行以下命令,进入 Hive 命令行。
hive

返回信息如下所示时,表示进入 Hive 命令行

Hive Session ID = aaa9c23d-4975-4c10-bb9a-1817c5fa36e6
Logging initialized using configuration in file:/etc/emr/hive/conf/hive-log4j2.properties Async: true
Hive Session ID = 258437d2-f601-42c9-bab3-731b975b0642


2.2 方式二:通过 beeline

使用 beeline 命令

beeline -u "jdbc:hive2://<HiveServer2地址>:10000/" -n <username> -p <password>

说明

  • HiveServer2地址获取方式,详见“确定 HiveServer2 地址”。
  • 命令行传递的 username 和 password 参数来自您在 EMR 控制台 > 集群详情 > 用户管理页面,通过 IAM 用户导入或手动添加的用户名和密码信息。详情参看用户管理

输入密码后,会得到信息:

Connecting to jdbc:hive2://<HiveServer2地址>:10000/
Connected to: Apache Hive (version 3.1.3-ve-2)
Driver: Hive JDBC (version 3.1.3-ve-2)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 3.1.3-ve-2 by Apache Hive
0: jdbc:hive2://<HiveServer2地址>:10000/>

表示已成功连接到 Hive。

2.3 方式三:通过 JDBC

  1. 创建 Maven 工程
mvn archetype:generate -DgroupId=com.example -DartifactId=hivejdbc -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  1. 添加 pom 依赖
<dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-jdbc</artifactId>
      <version>3.1.2</version>
</dependency>
  1. 使用 hive jdbc 连接数据库
package com.example;

import java.sql.*;

/**
 * Hello world!
 *
 */
public class App
{
    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();
        }

        // LDAP 中的用户名
        String user = "hive";

        // LDAP 中的用户密码,
        String password = "*******";

        Connection con = DriverManager.getConnection(
                "jdbc:hive2://<HiveServer2地址>:10000", user, password);

        Statement stmt = con.createStatement();

        String sql = "show databases";
        ResultSet res = stmt.executeQuery(sql);

        while (res.next()) {
            System.out.println(res.getString(1));
        }

    }
}