【问题标题】:String buffer fails to write data to database table字符串缓冲区无法将数据写入数据库表
【发布时间】:2019-05-31 15:02:35
【问题描述】:

我正在将 mongo 数据库移植到 PostgreSQL 数据库,但遇到了一个问题。我正在使用psycopg2COPY_FROM,它将文件对象、要写入的表和其他可选参数作为参数。我的原始代码如下所示:

records = '\n'.join(','.join([row['id'], row['att1'], row['att3']]) for row in data)
fio = io.StringIO(records)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()

上面的代码工作正常,但对于包含逗号的列(以逗号分隔)失败。因此,我想避开所有可能干扰的逗号和其他标点符号。为此,我使用了 Python 的 csv 模块来处理这个问题并得到以下代码:

fio = io.StringIO()
writer = csv.writer(fio)
writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()

使用上面的代码,mytable 无论如何都保持为空。我在写完行后尝试迭代fio,内容与初始代码sn-p中的相同(使用','.join)。我还检查了对象的大小,写入记录后它在两个 sn-ps 中的大小大致相同。

我在这里缺少什么?为什么第二个例子中的表没有写入数据?

【问题讨论】:

    标签: python-3.x postgresql stringio csv-write-stream


    【解决方案1】:

    在写信给fio 之后,你就到了文件的末尾。当 psycopg2 读取它时,您需要返回到开头。

    简单的修改,像这样:

    fio = io.StringIO()
    writer = csv.writer(fio)
    writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)
    
    fio.seek(0) # Return to beginning of file.
    
    cursor.copy_from(fio, 'mytable', sep=',')
    postgres.commit()
    

    【讨论】:

    • 啊!我不知道迭代器会指向文件的末尾。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多