Python无法在表中插入字符串

1 投票
2 回答
9453 浏览
提问于 2025-04-18 11:00

我写了一个可以动态更新表格的代码。它能输出结果,但我只能插入整数,输入字符串时就会出现“操作错误”。我尝试修改表格字段的数据类型,但仍然只能接受整数。我觉得程序内部需要做一些改动。请帮帮我:

这是我的代码:

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)

2 个回答

2

我觉得这样更好:

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

MySQLdb 来处理变量的格式化工作就行了,你不需要自己加引号,这样更安全。

这里

6

我觉得你需要为字符串加上 '%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 转换成 int(整数);year 转换成 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

撰写回答