gpt4 book ai didi

python - 无法将值插入 QSqlDatabase

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:36 25 4
gpt4 key购买 nike

from PyQt4 import QtGui,QtSql

def start_prestige():
m_name = "Prestige"
m_desc = " The Prestige is a 2006 Britis-American mystery thriller film directed by Christopher Nolan, from a screenplay adapted by Nolan and his brother Jonathan from Christopher Priest's 1995\n\n novel of the same name." \
" Its story follows Robert Angier and Alfred Borden, rival stage magicians in London at the end of the 19th century. Obsessed with creating the best stage illusion, they\n\n engage in competitive one-upmanship with tragic results." \
" The film stars Hugh Jackman as Robert Angier, Christian Bale as Alfred Borden, and David Bowie as Nikola Tesla. It also stars Scarlett\n\nJohansson, Michael Caine, Piper Perabo, Andy Serkis, and Rebecca Hall." \
" The film reunites Nolan with actors Bale and Caine from Batman Begins and returning cinematographer Wally Pfister,\n\n production designer Nathan Crowley, film score composer David Julyan, and editor Lee Smith."
m_director = "Christopher Nolan"
cast = "Hugh Jackman , Christian Bale , Scarlett Johansson , Michael Caine"
duration = 130
something(789, m_name, m_director, cast, m_desc, duration)

def something(id, title, director, cast, description, duration):
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('db/test.db')
if not db.open():
QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
QtGui.qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n" "Click Cancel to exit."),
QtGui.QMessageBox.Cancel)

return False

query = QtSql.QSqlQuery()
query.exec_(
"create table movie(id INT PRIMARY KEY , title VARCHAR(20), description VARCHAR(1000), director VARCHAR(100), cast VARCHAR(100), duration_min INT")
query.prepare("INSERT INTO movie VALUES(?,?,?,?,?,?)")
query.addBindValue(id, title, description, director, cast, duration)
if query.exec_():
db.commit()

start_prestige()

这里的问题是我无法将值插入数据库,因为它显示类型错误:

TypeError: QSqlQuery.addBindValue(QVariant, QSql.ParamType type=QSql.In): argument 2 has unexpected type 'str'

最佳答案

您一次只能添加一个个绑定(bind)值。所以你必须这样做:

query.prepare("INSERT INTO movie VALUES(?,?,?,?,?,?)")
query.addBindValue(id)
query.addBindValue(title)
query.addBindValue(description)
query.addBindValue(director)
query.addBindValue(cast)
query.addBindValue(duration)

或者类似的东西:

def something(*args):
...
query.prepare("INSERT INTO movie VALUES(?,?,?,?,?,?)")
for arg in args:
query.addBindValue(arg)

addBindValue 调用的顺序必须与 SQL 语句中占位符的数量和顺序匹配。

关于python - 无法将值插入 QSqlDatabase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46975381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com