Python之大數據庫hive實戰

今天和大家分享的是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庫的方法是實際可行的。感興趣的可以複製代碼修改對應的參數進行實操一下喲~

備註:我的個人公衆號已正式開通,致力於測試技術的分享,包含:大數據測試、功能測試,測試開發,API接口自動化、測試運維、UI自動化測試等,微信搜索公衆號:“無量測試之道”,或掃描下方二維碼:

 添加關注,一起共同成長吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章