可以使用 Python 中的 PyHive 库来连接 Hive 数据库。以下是连接 Hive 数据库的基本步骤:

  1. 安装 PyHive 库

可以使用以下命令安装 PyHive 库:

pip install pyhive[hive]
  1. 导入必要的库

导入 PyHive 库中的 Hive 连接器和游标:

from pyhive import hive
from TCLIService.ttypes import TOperationState
  1. 建立连接

使用以下代码建立与 Hive 服务器的连接:

conn = hive.Connection(host='HiveServer2 IP地址', port=10000, username='用户名', database='数据库名', auth='KERBEROS', kerberos_service_name='hive')

其中,auth 参数为认证方式,可以是 NONE、LDAP、KERBEROS 等,此处使用 KERBEROS;kerberos_service_name 参数为 Kerberos 服务名,可以根据实际情况进行修改。

  1. 执行查询

使用以下代码执行 SQL 查询:

cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
for result in cursor.fetchall():
    print(result)

其中,table_name 为要查询的表名。

  1. 关闭连接

使用以下代码关闭连接:

cursor.close()
conn.close()

完整代码示例:

from pyhive import hive
from TCLIService.ttypes import TOperationState

# 建立连接
conn = hive.Connection(host='HiveServer2 IP地址', port=10000, username='用户名', database='数据库名', auth='KERBEROS', kerberos_service_name='hive')

# 执行查询
cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
for result in cursor.fetchall():
    print(result)

# 关闭连接
cursor.close()
conn.close()
Python 连接 Hive 数据库教程:入门指南及完整代码示例

原文地址: https://www.cveoy.top/t/topic/na7G 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录