Python 连接hive

两种方式

  1. pyHive
  2. impyla

第一种

需要安装以下文件包

pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive

在mac中使用pycharm都可以成功安装,在windows中sasl可能会安装失败。需要使用whl文件本地安装。whl文件下载地址如下https://www.lfd.uci.edu/~gohlke/pythonlibs/#sasl我安装的是sasl‑0.2.1‑cp37‑cp37m‑win_amd64.whl这个版本。可根据自己python版本号与电脑下载相应的版本。

使用pip安装 pip install sasl‑0.2.1‑cp37‑cp37m‑win_amd64.whl

此时还需要将hive-site.xml文件中添加一下内容

<property>
<name>hive.server2.authentication</name>
<value>NONE</value>
</property>

此时还需要在hive中打开hiveserver2服务。
hive --service hiveserver2(开启远程连接服务)

然后使用

from pyhive import hive

conn = hive.Connection(host='xxxxxx', port=10000, auth='NOSASL',username="root",database='default')
cursor=conn.cursor()
cursor.execute('select * from employees limit 10')
for result in cursor.fetchall():
     print(result)       

就可以连接hive了。

简单封装一下

from pyhive import hive

class pyhive_help():

    def __init__(self,host,port=10000,username="root",database="default"):
        self.conn = hive.Connection(host=host, port=port, username=username, auth="NOSASL", database=database)


    def query(self,sql):
        cursor = self.conn.cursor()
        try:
            cursor.execute(sql)
            return cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            cursor.close()


第二种

需要安装以下文件包

pip install sasl(上述有讲怎么安装)
pip install thrift
pip install thrift-sasl
pip install impyla

此时还需要将hive-site.xml文件中添加一下内容

<property>
<name>hive.server2.authentication</name>
<value>NONE</value>
</property>

此时还需要在hive中打开hiveserver2服务。
hive --service hiveserver2(开启远程连接服务)

然后使用

from impala.dbapi import connect
conn = connect(host='xxxx', port=10000, database='default',auth_mechanism='NOSASL',user='root')
curs = conn.cursor()
curs.execute('SHOW DATABASES')
print(curs.fetchall())

放张图吧(没有骗你们)

from impala.dbapi import connect


class pyhive_help():

    def __init__(self,host,port=10000,username="root",database="default"):
        self.conn = connect(host=host, port=port, user=username, auth_mechanism="NOSASL", database=database)

    def query(self,sql):
        cursor = self.conn.cursor()
        try:
            cursor.execute(sql)
            return cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            cursor.close()

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值