安装
"""
pip install pyhs2
等待这个模块安装完成之后不要关闭命令行,接着在新的一行去执行命令。此时这个命令的作用是开启hive服务,否则python程序无法成功连接,命令如下:
hive --service hiveserver
这个是启动hive
"""
python3.7 利用pyhive 连接上hive
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
使用
from pyhive import hive
conn = hive.Connection(host='10.8.13.120', port=10000, username='hdfs', database='default')
cursor = conn.cursor()
cursor.execute('show tables')
for result in cursor.fetchall():
print(result)
cursor.close()
conn.close()
示例
from __future__ import print_function
import thrift
import requests
import sys
import json
import sqlite3
import pymssql
import pandas as pd
from pyhive import hive
from pyhive import presto
PY3 = 1 if sys.version > '3' else 0
class BaseConn(object):
def __init__(self, **config):
self.config = config
def build_connection(self):
pass
def init_from_json(self, json_file):
with open(json_file) as f:
self.config = json.load(f)
self.build_connection()
def read_df(self, sql):
return pd.read_sql(sql, self.con)
def execute(self, sql):
cursor = self.con.cursor()
try:
cursor.execute(sql)
res = cursor.fetchall()
return res
except Exception as e:
raise e
def iter_execute(self, sql):
"""将结果做成一个生成器"""
cursor = self.con.cursor()
try:
cursor.execute(sql)
while True:
one = cursor.fetchone()
if one is None:
break
else:
yield one
except Exception as e:
raise e
def __del__(self):
if self.con:
self.con.close()
class PrestoConn(BaseConn):
def __init__(self, **config):
if PY3:
super().__init__(**config)
else:
super(PrestoConn, self).__init__(**config)
def build_connection(self):
self.con = presto.connect(**self.config)
class HiveConn(BaseConn):
def __init__(self, **config):
if PY3:
super().__init__(**config)
else:
super(HiveConn, self).__init__(**config)
def build_connection(self):
self.con = hive.connect(**self.config)
class SqliteConn(BaseConn):
def __init__(self, **config):
if PY3:
super().__init__(**config)
else:
super(SqliteConn, self).__init__(**config)
def build_connection(self):
self.con = sqlite3.connect(**self.config)
class MssqlConn(BaseConn):
def __init__(self, **config):
if PY3:
super().__init__(**config)
else:
super(MssqlConn, self).__init__(**config)
def build_connection(self):
self.con = pymssql.connect(**self.config)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix