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_nameresult = connection.execute(text(sql_query)).fetchall()# 将查询结果转换为 Pandas DataFrameret_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("数据为空")