首页 > 解决方案 > CS50 Web Programming - 导入 books.csv 文件时出现 Postgres SQL 错误

问题描述

在我的 Postgres 数据库中,我制作了一Table本书。在书中,我有 5 列 - id, title, author, isbn, year.

我正在运行如下所示的 import.py 代码来导入 books.csv 内容:-

import csv
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


def main():
    f = open("books.csv")
    reader = csv.reader(f)
for isbn, title, author, year in reader:
    db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)",
               {"isbn": isbn, "title": title, "author": author, "year": year})
    print(f"Added book with isbn {isbn}.")
db.commit()


if __name__ == "__main__":
    main()

当我尝试导入我的列时,import.py在 git bash 上运行 python 时出现以下错误:

psycopg2.DataError: invalid input syntax for integer: "isbn"
LINE 1: ...RT INTO books (isbn, title, author, year) VALUES ('isbn', 't...

.. [SQL: 'INSERT INTO books (isbn, title, author, year) VALUES (%(isbn)s, %(title)s, %(author)s, %(year)s)']
   [parameters: {'isbn': 'isbn', 'title': 'title', 'author': 'author', 'year': 'year'}] 
   (Background on this error at: http://sqlalche.me/e/9h9h)

import.py 无法与创建的表对话。在 psql 中检查表时会出现该表。但是,当我尝试通过 psql 中的命令行创建不同的表时,它不起作用。

                                                         ^

标签: pythondatabasepostgresqlpython-importcs50

解决方案


您已经在另一个数据库中创建了表,从您使用 Python 连接的数据库中创建了该表,或者您已将其命名为其他名称

我会检查你创建它的工具......


推荐阅读