Python连接Hive实例教程

一 Python连接hive环境实例

经在网络查询相关的教程,发现有好多的例子,发现连接底层用的的驱动基本都是pyhive和pyhs2两种第三方库的来连接的 hive,下面将简介windows 10 python 3.10 连接hive的驱动程序方式,开发工具:pycharm ,经过测试已成功,分享给大家,有什么问题,可私信与我。

1 第一种:Python安装支持hive相关的库(pyhive)

1.1 安装sasl,本人建议采用离线安装方式,减少在线自动版本解决的问题

1.1.1 查询python版本 ,在命令下执行如下命令,如果不行,请查阅相关python安装教程

复制代码
python --version

如下图所示

1.1.2 下载sasl相应版本的库(whl), 此处++特别注意版本++,如果版本不一致,导致不能安装同时使用

我的python为python 3.10的,

cp310:表示为python的版本,为python 3 10的

win_amd64:表示为驱动为windows 64位的驱动

下载网址(包括其他离线库和包):sasl下载版本地址https://www.lfd.uci.edu/~gohlke/pythonlibs/#sasl

相应包:sasl-0.3.1-cp310-cp310-win_amd64.whl在

复制代码
pip install  sasl-0.3.1-cp310-cp310-win_amd64.whl

1.1.3 安装sasl,切换python环境的根目录,命令为

复制代码
pip install  sasl-0.3.1-cp310-cp310-win_amd64.whl

如下图所示,此处显示已安装成功的提示


1.2 安装thrift,命令如下,此处没有特别注意事项,如果有的话,请联系我

复制代码
pip install thrift

如下图所示

1.3 安装thrift_sasl,命令如下

复制代码
pip install thrift_sasl

1.4 安装phhive,命令如下

复制代码
pip install pyhive

如下图所示,已安装提示

2 第二种: Python安装支持hive相关的库(pyhs2)

2.1 如果安装中,有提供c++的库或相关工具,建立直接执行c++库包,我本采采用的360的全部C++库的安装方式,此方法简单明了,减少缺包的情况;或到微信官网下功相应的包安装。

注:此步要很重要

2.1 安装命令如下

复制代码
pig install  pyhs2

二 Python开发实例


1 (本人推荐)使用pyhive和pandas连接和操作数据库,使用ORM框架(sqlalchemy)的
create_engine连接数据库,,代码如下
复制代码
from pyhive import hive
import pandas as pd
import thrift_sasl
import puresasl
import sasl

# 定义数据库连接
from sqlalchemy import create_engine,types


# 读取数据
def select_pyhive(sql):
    # 创建hive连接

    engine = create_engine("hive://10.88.221.112:10000/ods")

    try:
        df = pd.read_sql(sql, engine)
        return  df
    finally:
        if engine:
            engine.dispose()


#执行函数
df=select_pyhive('SHOW DATABASES')
print(df)
2 使用pyhive和pandas连接和操作数据库,使用pyhive中的connection来连接hive,代码如下
复制代码
from pyhive import hive
import pandas as pd

# 读取数据
def select_pyhive(sql):
    # 创建hive连接
    conn = hive.Connection(host='10.88.221.112', port=10000, username='hive', password='hive',database='ods')

    try:
        df = pd.read_sql(sql, conn)
        return  df
    finally:
        if conn:
            conn.close()



#执行函数
df=select_pyhive('SHOW DATABASES')
print(df)
相关推荐
花酒锄作田14 分钟前
使用 pkgutil 实现动态插件系统
python
前端付豪4 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽4 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战5 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋11 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama