python中的mysqldb错误

2024-04-18 09:10:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Python将一个值插入到我的本地MySQL实例中,但是我不断得到一个错误

这是我的密码:

con = mdb.connect('localhost', 'root', 'password', 'testDB')
cur = con.cursor()
cur.execute('''INSERT INTO testDB.testPython VALUES (%s)''',("HelloWorld"))
con.commit()

但我得到以下错误

TypeError: not all arguments converted during string formatting

有人知道为什么吗?你知道吗


Tags: 实例localhost密码executeconnect错误mysqlroot
2条回答

TypeError是一个基本的Python错误:

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

你的问题是你忘了在元组中放置逗号,没有它就会被认为是括号中的对象:你的单个字符串。你知道吗

翻译讲解:

In [1]: ('Hello')
Out[1]: 'Hello'
In [2]: ('Hello',)
Out[2]: ('Hello',)

这样解决你的问题:

cur.execute('INSERT INTO testDB.testPython VALUES (%s)', ("HelloWorld",))

不要使用三重引号,这会将包含参数的sql视为字符串文本。改用标准引号(“)。你知道吗

相关问题 更多 >