在网上找了很多python连接hive的教程,很多只是看起来厉害,其实很多错。在本例中展示python用pyhs2包连接hive。
环境:windows10
hive版本:1.2.2(centos)
首先请确保你的hive开启了hiveserver2服务。
开启命令:hive --service hiveserver2
其次,请确保你的python安装了pyhs2包,具体安装包请网上下载。(在安装pyhs2包前请先安装sasl包,否则有可能出错)
好我们来看代码:
import pyhs2
with pyhs2.connect(host='192.168.131.130',
port=10007,
# authMechanism='NONE',
authMechanism='NOSASL',
user='hdfs',
password='',
database='default')as conn:
with conn.cursor() as cur:
print cur.getDatabases()
cur.execute("show databases")
for i in cur.fetch():
print i
这里对代码进行解释:
host为IP地址,port为hive端口号(一般默认为10000),authMechanism请在hive的配置文件中进行设置为‘NOSASL’,user为用户名,password为密码,database为连接的数据库名。
cur.execute为运行某命令。
而cur.fetch()为取回执行结果(为一个list)。