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

标签 python mysql python-2.7

我一直在尝试将 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/

相关文章:

Python:知道给定日期的下个月的第二个星期三

python - 考虑到 takewhile (itertools) 的最后一次迭代

python - 理解 One Line For 循环

php - 记录用户操作和页面浏览量的最有效方式是什么?

python - 使用 json.dumps() 时出现 UnicodeDecodeError

python - 如何在 Python 中按特定数字自动递增重复值?

python - '__main__' 在 type() 的输出中意味着什么

python - 更快的 3D 矩阵操作 - Python

mysql - 如何为具有相同 ID 的多行获取多个最大列值?

mysql - Join 给出了意想不到的(但令人愉快的)结果