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 数据库信息
相关推荐
方安乐1 天前
python之向量、向量和、向量点积
开发语言·python·numpy
zh1570231 天前
JavaScript中WorkerThreads解决服务端计算瓶颈
jvm·数据库·python
代码AI弗森1 天前
一文理清楚“算力申请 / 成本测算 / 并发评估”
java·服务器·数据库
小小小米粒1 天前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
蜡台1 天前
Python包管理工具pip完全指南-----2
linux·windows·python
Mr.朱鹏1 天前
【Python 进阶 | 第四篇】Psycopg3 + Flask 实现 PostgreSQL CRUD 全流程:从连接池到RESTful接口
python·postgresql·flask·virtualenv·fastapi·pip·tornado
摇滚侠1 天前
expdp 查看帮助
java·数据库·oracle
czhc11400756631 天前
C# 428 线程、异步
开发语言·c#
流年似水~1 天前
MCP协议实战:从零搭建一个让Claude能“看见“数据库的工具服务
数据库·人工智能·程序人生·ai·ai编程
2401_871492851 天前
Vue.js监听器watch利用回调函数处理级联下拉框数据联动
jvm·数据库·python