gpt4 book ai didi

mysql - 通过python从mysql导出的数据添加字段分隔符和引号

转载 作者:行者123 更新时间:2023-11-29 18:36:36 25 4
gpt4 key购买 nike

我编写了这个 python 脚本来从数据库中提取数据,它为我提供了我需要的数据,但我希望用命令分隔字段,并将每行用双引号括起来。例如:

我目前得到:

数据0数据1数据2数据3

我想得到:“数据0”,“数据1”,“数据2”,“数据3”

我尝试添加由\"包围的字段,但收到错误:
pymssql.OperationalError:(156,“关键字“BY”附近的语法不正确。DB-Lib 错误消息 156,严重性 15:\n一般 SQL Server 错误:检查来自 SQL Server 的消息\n”)。感谢任何帮助。

    #!/usr/bin/python

import pymssql as dbi
from collections import defaultdict

db_h = "1.2.3.4"
db_d = "DB"
db_u = "user"
db_p = "PW"

con = dbi.connect(db_h,db_u,db_p,db_d)
cur = con.cursor()

SQL = ("SELECT data0,data1,data2,data3"
"FROM mytable")

cur.execute(SQL)
for row in cur.fetchall():
print row[0], row[1], row[2], row[3]

cur.close
con.close

最佳答案

为了获得我想要的格式,我使用了:

  NewFile = open(File,'a')
NewFile.write("\"" + row[0] + "\"" + ", " + "\"" + row[1] + "\"" + ", " + "\"" + row[2] + "\"" + ", " "\"" + row[3] + "\"" + ")\n")
NewFile.close()

关于mysql - 通过python从mysql导出的数据添加字段分隔符和引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com