Python动态输入,更新表格

1 投票
2 回答
1603 浏览
提问于 2025-04-18 10:59

我写了一个程序,目的是为了动态更新一个数据库表格,但我遇到了一个错误。我把我知道的东西都塞进了这个程序里。以下是我的代码:

import MySQLdb
class data:
    def __init__(self):
        self.file123 = raw_input("Enter film: ")
        self.title_ = raw_input("Enter film: ")
        self.year = raw_input("Enter year: ")
        self.director = raw_input("Enter director: ")
a=data()

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

cursor = db.cursor()

cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()

这是我遇到的错误:

File "C:\Python27\maybe1.py", line 20, in <module>
 cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
      File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
        query = query % db.literal(args)
    TypeError: not all arguments converted during string formatting

我该如何解决这个问题呢?

2 个回答

1

我会这样做:

query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)

cursor.execute(query)

把%s替换成正确的数据类型,不然它会把所有东西都当成字符串来处理,这可能会在表格层面出问题。

1

你应该把 ? 改成 %s

这里有个问题,讲的是为什么mysqldb要用 %s 而不是 ?

撰写回答