Python基于starrocks库连接查询StarRocks数据库

Python基于starrocks库连接查询StarRocks数据库

SQLAlchemy 用法
要使用 SQLAlchemy 连接到 StarRocks,连接字符串如下所示:

starrocks://<User>:<Password>@<Host>:<Port>/<Catalog>.<Database>
import pandas as pd
from sqlalchemy import create_engine, text

# 设置 pandas 显示选项以显示所有列
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_colwidth', None)

"""
'starrocks://<User>:<Password>@<Host>:<Port>/<Catalog>.<Database>'
"""
def query_user_data(user_name):
    # 连接到StarRocks数据库
    engine = create_engine('starrocks://test_user:test_user123@192.168.1.2:9030/sr_db')

    # 执行查询并获取结果
    with engine.connect() as connection:
        sql_query = "select data from sr_db.user where user_name=" + user_name
        result = connection.execute(text(sql_query)).fetchall()

    # 将查询结果转换为 Pandas DataFrame
    ret_df = pd.DataFrame(result)
    return ret_df

# main function
if __name__ == '__main__':
    console = Console()
    user_name = "'tom'"
    df = query_user_data(user_name )
    # 如果 DataFrame 不为空,显示
    if df is not None and not df.empty:
        print(df)
    else:
        print("数据为空")

作者:数智客栈

物联沃分享整理
物联沃-IOTWORD物联网 » Python基于starrocks库连接查询StarRocks数据库

发表回复