我是一名新的 Python 程序员,正在尝试使用 Python 脚本将示例 CSV 文件导入我的 Postgres 数据库。
我有一个名为 abstable1 的 CSV 文件,它有 3 个标题:
absid, name, number 我在一个文件夹中有很多这样的文件,我想在 PostgreSQL 中创建一个与所有 CSV 文件同名的表。
这是我试图为一个文件创建一个表以进行测试的代码:
import psycopg2
import csv
import os
#filePath = 'c:\\Python27\\Scripts\\abstable1.csv'
conn = psycopg2.connect("host= hostnamexx dbname=dbnamexx user= usernamexx password= pwdxx")
print("Connecting to Database")
cur = conn.cursor()
#Uncomment to execute the code below to create a table
cur.execute("""CREATE TABLE abs.abstable1(
absid varchar(10) PRIMARY KEY,
name integer,
number integer
)
""")
#to copy the csv data into created table
with open('abstable1.csv', 'r') as f:
next(f)
cur.copy_from(f, 'abs.abstable1', sep=',')
conn.commit()
conn.close()
这是我得到的错误:
File "c:\Python27\Scripts\testabs.py", line 26, in <module>
cur.copy_from(f, 'abs.abstable1', sep=',')
psycopg2.errors.QueryCanceled: COPY from stdin failed: error in .read() call: exceptions.ValueError Mixing iteration and read methods would lose data
CONTEXT: COPY abstable1, line 1
非常感谢任何解决此问题的建议或替代解决方案。
白衣非少年
慕雪6442864
临摹微笑
相关分类