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

Robot Framework执行PostgreSQL查询如何直接获取CSV格式结果?

在Robot Framework中从PostgreSQL查询直接获取CSV格式结果

一、处理现有DatabaseLibrary结果并生成CSV(兼容Decimal类型)

默认Query返回字典列表,遇到Decimal等特殊类型时,json或pandas转换会失效,建议用Python的csv模块手动处理,自定义Robot关键字实现:

  1. 先获取查询结果和列名:

    ${results}=    Query    SELECT * FROM myTable
    # 提取列名(从第一个结果字典的键中获取)
    ${columns}=    Get Dictionary Keys    ${results}[0]
    
  2. 编写自定义Python函数(可放在Robot资源文件或自定义库中),处理Decimal并生成CSV内容:

    import csv
    from io import StringIO
    from decimal import Decimal
    
    def results_to_csv(results, columns):
        output = StringIO()
        writer = csv.writer(output)
        # 写入表头
        writer.writerow(columns)
        # 逐行处理数据,兼容Decimal类型
        for row in results:
            processed_row = []
            for col in columns:
                value = row[col]
                if isinstance(value, Decimal):
                    # 按需转成字符串或浮点数
                    processed_row.append(str(value))
                    # 也可使用 processed_row.append(float(value))
                else:
                    processed_row.append(value)
            writer.writerow(processed_row)
        return output.getvalue()
    
  3. 在Robot中调用函数生成CSV:

    ${csv_content}=    Run Keyword    results_to_csv    ${results}    ${columns}
    # 可选:将CSV内容保存到文件
    Create File    output.csv    ${csv_content}
    

二、修改DatabaseLibrary的返回格式(避免字典)

DatabaseLibrary 3.2.2版本中,Execute Sql String关键字默认返回列表的列表(而非字典),可以直接基于这个结果生成CSV:

${results}=    Execute Sql String    SELECT * FROM myTable
# 获取列名(需额外查询一次)
${col_names}=    Query    SELECT column_name FROM information_schema.columns WHERE table_name='myTable'
# 提取列名列表
${columns}=    Create List
FOR    ${row}    IN    @{col_names}
    Append To List    ${columns}    ${row}[column_name]
END
# 后续用同样的CSV处理逻辑生成内容

三、替代库推荐

如果不想自定义处理,可尝试以下专用库:

  • Psycopg2Library:基于psycopg2的PostgreSQL专用库,支持配置返回格式,部分版本内置CSV导出关键字,能更好适配PostgreSQL的特殊数据类型。
  • DataDriverLibrary:结合数据驱动能力,支持直接将数据库查询结果导出为CSV,内置复杂数据类型的处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:55:10