我为动态更新表做了编码。它给了我输出,但我只能插入整数而不是字符串它给我“操作错误”如果我输入字符串,我尝试改变表字段数据类型,但它仍然只接受整数,我认为它需要在程序内进行更改。请帮忙:
这是我的代码:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
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()
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
db.commit()
db.close()
我应该更改什么才能接受整数和字符串作为输入?请帮助
错误:
Enter film: 123
Enter title: adarsh
Enter year: 1234
Enter director: 132
**error**
Traceback (most recent call last):
File "C:\Python27\maybe1.py", line 22, in <module>
cursor.execute(query)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'adarsh' in 'field list'")
数据类型: file123 int(11),title_ varchar(50),year int(11),director varchar(12)
答案 0 :(得分:4)
我认为您需要为字符串添加'%s'
,为整数添加%s
query = "INSERT INTO films (file123, title_, year, director) VALUES ('%s', '%s', %s, '%s')" % (a.file123, a.title_, a.year, a.director)
或
query = "INSERT INTO films (file123, title_, year, director) VALUES (?,?,?,?)"
curs.excute(query,[a.file123, a.title_, a.year, a.director])
解释您的代码有什么问题:
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
raw_input("Enter film: ")
始终为string
。所以你需要将每个变量转换为适当的类型,例如:file123 to int; year to int
现在
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
print query
它给出了
INSERT INTO films (file123, title_, year, director) VALUES (123, adars, 200, sundar)
但正确的格式应为
INSERT INTO films (file123, title_, year, director) VALUES (123, 'adars', 200, 'sundar')
由于%s
直接将值设为字符串而没有引号,因此而不是%s
使用?
答案 1 :(得分:2)
我认为这更好:
cursor.execute("INSERT INTO films (file123, title_, year, director) "
"VALUES (%s, %s, %s, %s)",
(a.file123, a.title_, a.year, a.director))
让MySQLdb
为您做变量格式化工作,您不需要自己添加引号,而且更安全。
Here就是例子。