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

如何将pymssql返回列表的分隔符从逗号改为竖线?

解决方案

pymssql返回的元组列表,其默认打印时的逗号分隔是Python元组的原生字符串表示,无法通过修改cursor参数直接改变分隔符。你需要手动处理查询结果的输出格式,具体实现如下:

修改后的代码

cnxn = pymssql.connect(
        server=db_server, 
        port=12345, 
        database='DataBase', 
        user=username, 
        password=password)

cursor = cnxn.cursor(as_dict=False)

# sql_statement = "SELECT Name FROM table"
cursor.execute(sql_statement)
rows = list(cursor.fetchall())

# 格式化输出内容
formatted_rows = []
for row in rows:
    # 将元组内的元素转为字符串后用竖线连接
    joined_content = '|'.join(str(item) for item in row)
    formatted_rows.append(f"('{joined_content}')")

# 拼接成目标格式并打印
print(f"[{', '.join(formatted_rows)}]")

代码说明

  • 遍历查询返回的每个元组,用'|'.join()将元组内的所有元素(先转为字符串以兼容非字符串类型字段)用竖线连接
  • 把每个连接后的字符串包裹为('内容')的形式
  • 最后将所有格式化后的字符串用逗号分隔,再包裹方括号,得到你期望的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:10:25