Python之大數據庫hive實戰


歡迎關注【無量測試之道】公眾號,回復【領取資源】,
Python編程學習資源干貨、
Python+Appium框架APP的UI自動化、
Python+Selenium框架Web的UI自動化、
Python+Unittest框架API自動化、

資源和代碼 免費送啦~
文章下方有公眾號二維碼,可直接微信掃一掃關注即可。

今天和大家分享的是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自動化測試等,微信搜索公眾號:“無量測試之道”,或掃描下方二維碼:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM