【问题标题】:Outputting SQL Data to a Text File with Python - How to get rid of None?使用 Python 将 SQL 数据输出到文本文件 - 如何摆脱无?
【发布时间】:2019-07-11 20:08:17
【问题描述】:

我正在使用 pyodbc python 代码从 SQL Server 表中提取数据。

在输出文件中我得到这样的记录:

1、1、无、无、无、无、无、无

SQL 表中的 None 值为 Null。

我想以这种格式查看文本文件中的记录。我不想看到无。

1, 1, , , , , ,

有什么想法可以做到这一点吗?

这是我正在使用的代码:

    import pyodbc

    outputfile = 'MyOut.txt'

    output_data = open(outputfile, 'w+')

    conn=pyodbc.connect(
        r'Driver={SQL Server};'
        r'Server=MyServer;’
        r'Database=MyData;'
        r'Trusted_Connection=yes;')

    crsr = conn.cursor()

    crsr.execute('select * from MyTable’)

    for row in crsr:
    print(str(row))
        outrows = str(row).strip('(')
        outrows = outrows.strip(')')
        output_data.write(outrows + '\n')

    output_data.close()

【问题讨论】:

    标签: sql-server python-3.x


    【解决方案1】:

    我知道outrows 是一个字符串,但使用列表可能会更容易。除此之外,输出可能是一个字符串,因为您正在写入一个 txt。
    你可以修改你的for循环

    for row in crsr:
        outrows = str(row).strip("(").strip(")")
        line = outrows.split(",")
        # creating the array, by splitting the string at each comma
        for component in line:
            if component == " None":
                # with " " as there is most likely a space after the "," in the file
                line[line.index(component)] = ""
        file.write(",".join(line)+"\n")
    

    恐怕我对pyodbc不是特别熟悉,但我希望这对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多