python 连接hive2 数据库

python 连接hive2 数据库

python 复制代码
from pyhive import hive

# 连接到 Hive
conn = hive.Connection(host='hive_host', port=10000, username='your_username')

# 创建游标对象
cursor = conn.cursor()

# 执行查询
cursor.execute('SELECT * FROM your_table LIMIT 10')

# 获取结果
for row in cursor.fetchall():
    print(row)

下面封装一下代码 完整代码如下所示:

python 复制代码
from pyhive import hive

class HiveDictCursor:
    """
    PyHive cursor 封装,fetchall / fetchone 返回字典列表或字典
    """
    def __init__(self, cursor):
        self._cursor = cursor
        self._columns = None

    def execute(self, sql, params=None):
        if params:
            self._cursor.execute(sql, params)
        else:
            self._cursor.execute(sql)
        # 获取列名
        self._columns = [col[0] for col in self._cursor.description]

    def fetchall(self):
        rows = self._cursor.fetchall()
        return [dict(zip(self._columns, row)) for row in rows]

    def fetchone(self):
        row = self._cursor.fetchone()
        if row:
            return dict(zip(self._columns, row))
        return None

    def __getattr__(self, name):
        # 其他方法直接代理给原 cursor
        return getattr(self._cursor, name)

#数据库的配置
HIVE_CONFIG = {
    'host': '127.0.0.1',
    'database': 'bdp',
    'username': 'wwww',
    'password': '123456',
    'port': 10000,
    'auth': 'LDAP'
}


#查询方法
def fetch_data_from_hivesql(query):
    conn = None
    cursor = None
    try:
        conn = hive.Connection(**HIVE_CONFIG)
        cursor = HiveDictCursor(conn.cursor())
        logging.info("执行 Hive SQL: %s", query)
        cursor.execute(query)
        result = cursor.fetchall()
        #result = [dict(row) for row in cursor.fetchall()] 
        return result
    except Exception as e:
        logging.error("从Hive获取数据时出错: %s", e)
        return []
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()



today = datetime.now().date()
yesterday = (today - timedelta(days=1)).strftime("%Y-%m-%d")
start_time = yesterday+" 00:00:00" 
end_time = yesterday+" 23:59:59"

aa_sql = """ SELECT * FROM ddd  WHERE gxsj>='{start_time}' AND gxsj<='{end_time}' ORDER """
query = aa_sql.format(start_time=start_time,end_time=end_time)
        
rows = fetch_data_from_hivesql(query) #查询hive 数据库信息
相关推荐
AC赳赳老秦2 分钟前
OpenClaw + 飞书多维表格:自动同步数据、生成统计图表、触发自动化任务
java·大数据·python·缓存·自动化·deepseek·openclaw
WangN26 分钟前
【通识】RSL-RL快速上手
人工智能·python·机器学习·机器人
南部余额6 分钟前
Canal解决MySQL与Redis数据一致性问题
数据库·redis·mysql·canal·数据·数据同步
geovindu7 分钟前
python: Reactor Pattern
开发语言·python·设计模式·反应器模式
1024+8 分钟前
在 ‌Ubuntu 24.04‌ 上安装 ‌Python 3.8‌
linux·python·ubuntu
财经资讯数据_灵砚智能9 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月15日
大数据·人工智能·python·信息可视化·自然语言处理
CS_SKILL12 分钟前
吉比特 C++ 实习一面面经:一轮把 C++、容器、并发、排序和网络全扫了一遍
java·开发语言·校招面经·实习面经·技术面经·吉比特校招
feifeigo12314 分钟前
基于多混沌映射的图像加密(MATLAB实现)
开发语言·matlab
techdashen17 分钟前
Go 语言仓库 Top 100 贡献者分析报告
开发语言·后端·golang
何以解忧,唯有..18 分钟前
Go 语言变量命名规范详解
开发语言·后端·golang