python - 无法将 csv 文件加载到 heroku 中的 postgres 表中 - 错误:整数类型的输入语法无效:
问题描述
Error in copying db invalid input syntax for type integer: "0"
CONTEXT: COPY spellbeeword_tb, line 1, column id: "0"
我的代码:
import os
import psycopg2
def writedb(conn):
cur = conn.cursor()
print("Started opening file to copy into table")
try:
with open("spellbee/docs/Spell_Bee_Word_db.csv", 'r', encoding="utf-8") as f:
sql_copy= "COPY spellbeeword_tb FROM stdin (FORMAT CSV)"
cur.copy_expert(sql=sql_copy,file=f)
print('successfully copied files into db')
# commit changes
conn.commit()
print("Committed changes")
except Exception as error:
print('Error in copying db ',error)
finally:
if conn:
conn.close()
f.close()
def main():
DATABASE_URL = os.environ['DATABASE_URL']
try:
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
writedb(conn)
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn:
conn.close()
if __name__ == "__main__" :
main()
operations = [
migrations.CreateModel(
name='BeeWord',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('level', models.CharField(max_length=10)),
('word', models.CharField(max_length=90)),
],
operations = [
migrations.AlterModelTable(
name='beeword',
table='spellbeeword_tb',
),
> 0 ONE gel
> 1 ONE day
> 2 ONE scorch
它在上面的示例 csv 数据上引发错误。
它不接受 csv 给出的整数值,我尝试给出最后两列,不包括 csv 中的索引。两种方式都不接受。请提供解决方案。
CSV 文件只包含没有标题的数据。我的 ORM 看起来像上面。
解决方案
COPY 命令生成一个标题行,导入命令将其作为数据读取。
告诉导入命令不要读取第一行。
为了避免生成标题行,我不知道如何默认省略
要忽略标题行,请在导入命令中插入 HEADER 选项,并在 csv 文件中插入标题。现在它工作正常
try:
with open("spellbee/docs/Spell_Bee_Word_db.csv", 'r', encoding="utf-8") as f:
#cur.copy_from(f,'spellbeeword_tb', sep=',')
sql_copy ="COPY spellbeeword_tb FROM STDIN WITH CSV HEADER DELIMITER ',' "
cur.copy_expert(sql=sql_copy,file=f)
print('successfully copied files into db')
# commit changes
conn.commit()
print("Committed changes")
except Exception as error:
print('Error in copying db ',error)
finally:
if conn:
conn.close()
print("Finally connection closed")
f.close()
推荐阅读
- javascript - 如何通过 Angular 中的路由在 Cloud Functions 中执行对 Cloud Firestore 的添加?
- ios - 在 UITableView 中至少选择一行
- ios - 从 AppDelegate 调用一个函数并使用该函数执行 segue
- wordpress - 更改“/shop”档案中的程序默认产品变体图像-Woocommerce
- r - 为什么我的 dplyr 语句会创建额外的行?
- c# - 使用通用扩展方法将实体映射到视图模型
- vba - VBA更改文件夹中所有文件的名称
- c# - 实体框架延迟加载总和子表慢
- c# - 使用锁来排队任务是一个好习惯吗?
- c# - 查找数据库中是否存在 300K 记录的最快方法