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 数据库信息
相关推荐
小白|2 分钟前
tensorflow:昇腾CANN的TensorFlow适配层
人工智能·python·tensorflow
Matlab程序猿小助手11 分钟前
【MATLAB源码-第319期】基于matlab的帝王蝶优化算法(MBO)无人机三维路径规划,输出做短路径图和适应度曲线.
开发语言·算法·matlab
码点滴14 分钟前
CRI-O选型与容器运行时标准
开发语言·人工智能·架构·kubernetes·cri-o
回眸&啤酒鸭15 分钟前
【回眸】嵌入式软件单元测试工具链实战指南
开发语言·单元测试·白盒测试
彦为君17 分钟前
JavaSE-10-并发编程(11个案例)
java·开发语言·python·ai·nio
石山代码18 分钟前
java前景
java·开发语言
10岁的博客20 分钟前
C++ 进制转换:通用 a 进制转 b 进制(2-36进制)题解
开发语言·c++
l1t28 分钟前
DeepSeek总结的在 DuckDB 中试驾 Lance 数据湖仓格式
数据库·人工智能·机器学习·duckdb
Cthy_hy29 分钟前
树状数组(BIT)进阶:差分优化实现区间修改、区间查询
数据结构·python·算法
码界筑梦坊34 分钟前
133-基于Python的全球城市生活成本数据可视化分析系统
开发语言·python·信息可视化·django·毕业设计·生活