gpt4 book ai didi

postgresql - Psycopg2 copy_from 抛出 DataError : invalid input syntax for integer

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

我有一个包含一些整数列的表。我正在使用 psycopg2 的 copy_from

conn = psycopg2.connect(database=the_database,
user="postgres",
password=PASSWORD,
host="",
port="")

print "Putting data in the table: Opened database successfully"
cur = conn.cursor()
with open(the_file, 'r') as f:
cur.copy_from(file=f, table = the_table, sep=the_delimiter)
conn.commit()
print "Successfully copied all data to the database!"
conn.close()

错误表明它希望第 8 列是整数而不是字符串。但是,Python 的 write 方法只能读取字符串到文件中。因此,当您的文件只能具有整数的字符表示(例如 str(your_number))时,您如何将一个充满数字字符串表示的文件导入到包含预期整数列的 postgres 表中。

您要么必须将整数格式的数字写入文件(Python 的 write 方法不允许这样做),要么 psycopg2 应该足够聪明以将转换作为 copy_from 过程的一部分,但显然不是。任何想法表示赞赏。

最佳答案

我最终使用了 copy_expert 命令。请注意,在 Windows 上,您必须设置文件的权限。这个帖子很有用setting permission .

with open(the_file, 'r') as f:            
sql_copy_statement = "copy {table} FROM '"'{from_file}'"' DELIMITER '"'{deli}'"' {file_type} HEADER;".format(table = the_table,
from_file = the_file,
deli = the_delimiter,
file_type = the_file_type
)
print sql_copy_statement
cur.copy_expert(sql_copy_statement, f)
conn.commit()

关于postgresql - Psycopg2 copy_from 抛出 DataError : invalid input syntax for integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275754/

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