【发布时间】:2021-07-06 14:26:36
【问题描述】:
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 如下所示。
【问题讨论】:
-
你确定 csv 列只有整数值吗?有些行可能有字符串,因此整列都被视为字符串。
-
已经在开发区-本地服务器的 sqlite3 中部署了相同的文件。现在我尝试将其移动到 heroku 环境中由于 heroku 不支持 sqlite3,我正在远程推进我使用过的 Postgres db copy_from 。我也试过 copy_expert 。 Postgres 的行为不同。我在我的数据库表中使用了驼峰式大小写。但同样的事情不适用于 postgres 。因此我重命名了表名。然后它工作。那么有什么办法可以解决这个问题
-
索引列中没有字符串。我可以从错误中招致一件事,即 cur.copy_expert 方法提取的 csv 数据是字符串,即使我们通过了数字。但在 sqlite3 中并非如此。 在错误类型整数中:“0” - 双引号内显示零。如何正确读取csv格式的文件?
标签: python csv django-models sqlbulkcopy heroku-postgres