Python操作Hive准备

教程中使用的是Java操作hive,而我的需求是使用python操作hive,所以需要进行简单的环境配置。
使用python操作hive有两种方式:
Thrift api方式和python hive相关的包
1、Thrift api方式
根据介绍,只需要把hive/lib/py包下的文件全部拷贝到python的扩展库文件夹下即可site-packages。
拷贝完成后,启动hiveserver2服务器,使用测试代码测试:

import sys
from hive_service import ThriftHive
from hive_service.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

def hiveExe(sql):

    try:
        transport = TSocket.TSocket('192.168.83.135', 10000)
        transport = TTransport.TBufferedTransport(transport)
        protocol = TBinaryProtocol.TBinaryProtocol(transport)
        client = ThriftHive.Client(protocol)
        transport.open()

        client.execute(sql)

        print "The return value is : "
        print client.fetchAll()
        print "............"
        transport.close()
    except Thrift.TException, tx:
        print '%s' % (tx.message)

if __name__ == '__main__':
    hiveExe("show databases adad;")

进行调试运行,发现走到client.execute(sql)这句时无法继续执行,目前还没找到解决办法。
2、使用pyhs2包操作hive(官方已经不再持续支持,但还可以用)
安装pyhs2依赖包:

yum install cyrus-sasl-plain
yum install cyrus-sasl-devel
yum install python-devel.x86_64
yum install cyrus-sasl-devel.x86_64

使用pip安装pyhs2
pip installpyhs2
测试代码如下:

import pyhs2

conn = pyhs2.connect(host='localhost',
                   port=11111,
                   authMechanism="PLAIN",
                   user='root',
                   password='test',
                   database='default')
cur = conn.cursor()
print cur.getDatabases()

代码执行结果如下图:
这里写图片描述
3、使用pyHive包操作hive,需要安装pyhive包,测试代码如下:

from pyhive import hive
from TCLIService.ttypes import TOperationState

# 打开hive连接
hiveConn = hive.connect(host='192.168.83.135',port=11111)
cursor = hiveConn.cursor()

# 执行sql语句
cursor.execute('show databases', async=True)

# 得到执行语句的状态
status = cursor.poll().operationState
print "status:",status

# 如果执行出错,循环执行,直到执行正确,可不要
while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
    logs = cursor.fetch_logs()
    for message in logs:
        print message
    # If needed, an asynchronous query can be cancelled at any time with:
    # cursor.cancel()
    status = cursor.poll().operationState

# 打印结果
print cursor.fetchall()

# 关闭hive连接
cursor.close()
hiveConn.close()

程序运行结果:
这里写图片描述
在之后的学习中,将使用pyhive进行操作。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值