You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python与Snowflake的execute_string方法获取记录时遇空DataFrame错误

问题描述

使用execute_string方法执行SQL查询后,返回的DataFrame为空,但手动执行相同SQL能得到预期的3行数据。


相关代码与信息

SQL查询语句

# 注意:原代码缺少字符串引号,已补充
query_string = "select table_name, column_name, ordinal_position FROM db.information_schema.columns WHERE table_schema = 'Schema' AND table_name = 'TABLE_CDC' and table_name not like '%_STG_LOAD' and table_name not like '%_STG_TABLE' and table_name not like '%\\_EXT' and table_name not like 'RECON%' and column_name not in ('RECORD_DELETE_IND', 'DATA_LOAD_SOURCE', 'DATA_UPDATE_SOURCE', 'DATA_LOAD_TIME', 'RECORD_MD5', 'SOURCE_SYSTEM_ID', 'DATA_UPDATE_TIME') order by table_name, ordinal_position;"

执行代码

col_cursor_list = conn.execute_string(query_string)
for col_cursor in col_cursor_list:
    df = pd.DataFrame(col_cursor.fetchall())
    csv_column_name = ','.join(df[1])

手动执行SQL的预期结果

Row  TABLE_NAME  COLUMN_NAME  ORDINAL_POSITION
1    TABLE_CDC   DEVICE        1
2    TABLE_CDC   AGE           2
3    TABLE_CDC   SEX           3

实际错误输出

Empty DataFrame

可能的解决方向

  1. 检查execute_string的返回结构
    不同数据库连接库的execute_string返回格式存在差异,可能返回多个游标或需要特殊读取方式。先打印游标状态确认数据是否存在:

    print(f"游标列表长度: {len(col_cursor_list)}")
    for idx, col_cursor in enumerate(col_cursor_list):
        print(f"游标{idx}行数: {col_cursor.rowcount}")
        df = pd.DataFrame(col_cursor.fetchall())
        print(f"游标{idx}数据:\n{df}")
    
  2. 修正SQL转义问题
    原SQL中的%\\_EXT在Python字符串中可能转义异常,改用原始字符串或单反斜杠:

    # 使用原始字符串避免转义问题
    query_string = r"select table_name, column_name, ordinal_position FROM db.information_schema.columns WHERE table_schema = 'Schema' AND table_name = 'TABLE_CDC' and table_name not like '%_STG_LOAD' and table_name not like '%_STG_TABLE' and table_name not like '%\_EXT' and table_name not like 'RECON%' and column_name not in ('RECORD_DELETE_IND', 'DATA_LOAD_SOURCE', 'DATA_UPDATE_SOURCE', 'DATA_LOAD_TIME', 'RECORD_MD5', 'SOURCE_SYSTEM_ID', 'DATA_UPDATE_TIME') order by table_name, ordinal_position;"
    
  3. 验证数据库与Schema匹配
    确认conn连接的是目标数据库,同时检查table_schema = 'Schema'的大小写是否符合数据库规则(部分数据库对Schema名称大小写敏感)。

  4. 改用常规游标执行
    绕过execute_string,直接用标准游标执行SQL,排除方法本身的潜在问题:

    cursor = conn.cursor()
    cursor.execute(query_string)
    # 手动指定列名,避免DataFrame列索引混乱
    df = pd.DataFrame(cursor.fetchall(), columns=['TABLE_NAME', 'COLUMN_NAME', 'ORDINAL_POSITION'])
    csv_column_name = ','.join(df['COLUMN_NAME'])
    

内容的提问来源于stack exchange,提问作者Manish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:21