gpt4 book ai didi

python - 使用 Python 2.7 将变量传递到 MySQL

转载 作者:行者123 更新时间:2023-11-29 11:21:29 24 4
gpt4 key购买 nike

我一直在尝试将 Python 2.7 中变量的字符串值插入到 MySQL 语句中。我似乎无法让它工作,有人可以指出我正确的方向吗?

import MySQLdb

country_name = raw_input("Which country would you like?\n")

dbh = MySQLdb.connect(host="localhost",
user="boole",
passwd="****",
db="mySQL_Experiment_1")
sth = dbh.cursor()
sth.execute("""SELECT name, population FROM world WHERE name=(%s)""", (country_name))
for row in sth:
print row[0], row[1]

它输出:

/usr/bin/python2.7 "/home/boole/Documents/Python Scripts/mySQL_Experiment_1/main.py"
Which country would you like?
Canada
Traceback (most recent call last):
File "/home/boole/Documents/Python Scripts/mySQL_Experiment_1/main.py", line 10, in <module>
sth.execute("""SELECT name, population FROM world WHERE name=(%s)""", (country_name))
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

谢谢, bool

最佳答案

试试这个

cursor.execute("SELECT name, population FROM world where name = %s", [country_name])

关于python - 使用 Python 2.7 将变量传递到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827994/

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