Python之大数据库hive实战

Python之大数据库hive实战

技术教程gslnedu2025-03-05 12:00:5710A+A-

今日分享主题:

Python如何连接hive数据库来进行hivesql的查询操作。


step1:环境准备

Python版本:3.6.2

Windows版本:Windows10版本的64位


step2:下载依赖的文件

(1)、.whl文件在https://www.lfd.uci.edu/~gohlke/pythonlibs/地址栏下载相应的python和windows版本的sasl和bitarray

如下截图所示,搜索对应的关键字找到对应的版本下载即可

(2)、下载至本地的目录地址为:D:\python\jar


step3:安装步骤

(1)、Win + R进入cmd命令行

(2)、cd到本地python的安装目录下

(3)、依次安装以下包

pip install six

pip install bit_array

pip install thriftpy (如果本地的python版本为2.X,则安装thrift,如果本地的python版本为3.X,则安装thriftpy)

pip install D:\python\jar\sasl-0.2.1-cp36-cp36m-win_amd64.whl

pip install thrift_sasl

pip install D:\python\jar\bitarray-1.2.2-cp36-cp36m-win_amd64.whl

pip install impyla

注意:安装完成后包的版本号如下

six 1.14.0

bit-array 0.1.0

bitarray 1.2.2

thriftpy 0.3.9

thrift-sasl 0.4.2

impyla 0.16.2

pure-sasl 0.6.2


step4:代码

具体代码示例如下所示:

from impala.dbapi import connect #导入connect模块
import warnings


def hive_connect(hive_sql):
    warnings.filterwarnings('ignore') #忽略warnings警告
    config_hive_beta = {
        'host': '10.7.89.88',  #hive的host地址
        'port': 10000,    #hive的端口号
        'user': 'hive',    #hive的username
        'password': 'hive',    #hive的password
        'database': 'tmp',     #hive中需要查询的数据库名
        'auth_mechanism': 'PLAIN' #hive的hive-site.xml配置文件中获取
    }
    conn = connect(**config_hive_beta)
    #conn = connect(**config_hive_beta)等价于
    #conn = connect(host='10.7.89.88', port=10000, user='hive', password='hive', database='tmp', auth_mechanism='PLAIN')
    cursor = conn.cursor()
    cursor.execute(hive_sql)
    hive_all_hotel = cursor.fetchall()
    print(hive_all_hotel)


使用:

hive_connect('select count(1) from tmp.tmp_test_table where dt="2020-05-27"')

调用该方法查询hive库里的tmp_test_table表的分区为2020-05-27的数据总条数时会报如下错误:

thriftpy.transport.TTransportException: TTransportException(type=1, message="Could not start SASL: b'Error in sasl_client_start (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'")

出现这个错误的主要原因是sasl和pure-sasl有冲突


step5:错误解决方法

解决方法如下:

(1)、Win + R进入cmd命令行

(2)、cd到本地python的安装目录下

(3)、卸载sasl:pip uninstall sasl

再次调用:

hive_connect('select count(1) from tmp.tmp_test_table where dt="2020-05-27"')

时,该方法正确地在控制台输出tmp_test_table表分区为2020-05-27的数据总条数为:29341023。


至此,报错完美解决。同时也证明了python连接hive库的方法是实际可行的。感兴趣的可以复制代码修改对应的参数进行实操一下哟~

点击这里复制本文地址 以上内容由朽木教程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

朽木教程网 © All Rights Reserved.  蜀ICP备2024111239号-8