两种方式
- pyHive
- 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()