如何将变量插入数据库表sqlite3 - Python

时间:2017-06-21 14:17:17

标签: python database sqlite

每当我尝试运行以下代码时,我都会收到错误消息,说没有这样的列" title_data",我真的很困惑因为" TITLE"列不是" title_data"

def insertData(self):
    title_Data = self.edit_title.text()
    year_Data = self.edit_year.text()
    rating_Data = self.edit_rating.text()


    connection = sqlite3.connect('films.db')
    try:
        connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(title_Data,year_Data,rating_Data)")


    except sqlite3.IntegrityError:
        print("You have already stored this data")
    connection.commit()
    connection.close()

1 个答案:

答案 0 :(得分:1)

您没有正确传递变量。而不是

connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(title_Data,year_Data,rating_Data)")

你应该使用

connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(?,?,?)", (title_Data,year_Data,rating_Data))

有关详细信息,请参阅execute()的文档。