插入语句返回绑定参数<x>需要一个值

时间:2019-09-19 07:45:03

标签: python-3.x postgresql csv flask sqlalchemy

我试图将CSV文件中的一行插入到Heroku网站上的Postgres数据库中,该代码访问该数据库,打开CSV文件并访问tha数据,而且还返回InvalidRequestError。

代码可以正确地从CSV文件中获取数据,我不知道自己在做什么错。

数据格式为CSV文件: 1416949658,《黑暗正在崛起》,苏珊·库珀,1973年

表结构:

CREATE TABLE books(
        id SERIAL PRIMARY KEY,
        isbn VARCHAR NOT NULL,                  
                title VARCHAR NOT NULL,
        author_name VARCHAR NOT NULL,
        publish_year INTEGER NOT NULL

);
for isbn, title, author_name, publish_year in reader:
    db.execute("INSERT INTO books (isbn, title, author_name, publish_year) VALUES (:isbn, :title, :author_name, :publish_year)",\
                {isbn: isbn, title: title, author_name: author_name, publish_year: publish_year})
    print(f"Added book {title} written by {author_name} with isbn {isbn} on year {publish_year}")
db.commit()
  

sqlalchemy.exc.StatementError:(sqlalchemy.exc.InvalidRequestError)A   绑定参数'isbn'所需的值[SQL:INSERT INTO书籍   (isbn,标题,author_name,publish_year)VALUES(%(isbn)s,%(title)s,   %(author_name)s,%(发布   _year)s);]] [参数:[{'1416949658':'1416949658','The Dark Is Rising':'The Dark Is Rising','Susan Cooper':'Susan Cooper','   1973':'1973'}]]

如您所见,它获取数据,但仍然返回错误。

1 个答案:

答案 0 :(得分:0)

  • 要从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 of ISBN {isbn} having Title: {title} written by  {author} in the year {year}.")
    db.commit()


if __name__ == "__main__":
    main()

这应该可以解决您的问题。您缺少python中的字典需要提供的{"key": value}格式。