gpt4 book ai didi

python无法在表中插入字符串

转载 作者:行者123 更新时间:2023-11-29 04:07:52 26 4
gpt4 key购买 nike

我为动态更新表做了编码。它给了我输出,但我只能插入整数而不是字符串,如果我输入字符串,它会给我“操作错误”,我尝试更改表字段数据类型,但它仍然只接受整数,我认为它需要在程序中进行更改。请帮助:

这是我的代码:

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)

最佳答案

我认为您需要为字符串添加 '%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;年到 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 使用 ?

关于python无法在表中插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405875/

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