用python查询和检索Mysql表中的数据

2024-04-27 01:15:48 发布

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

我正在尝试使用python从mysql表中检索数据,但不断出现错误。请看下面我的尝试和数据:

import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx", db="world")
cursor = db.cursor()
t=['red', 'yellow']

for x in t:
    cursor.execute("select * from mytable where colours=%s," [x])

我得到了以下错误:TypeError: string indices must be integers, not str

我学习了Mysql将数据存储为元组,因此我需要将%s更改为元组,但不知道如何更改。你知道吗

有什么建议吗?谢谢。你知道吗


Tags: 数据importlocalhosthostdbconnect错误mysql
2条回答

试试这个,看看这个能不能解决你的问题

import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx", db="world")
cursor = db.cursor()
t=['red', 'yellow']

for x in t:
    cursor.execute("select * from mytable where colours=%s" % repr(x))

请注意这里的Sql Query将像

select * from mytable where colours='red'   #which is actual and correct query

虽然我还没有测试,可能还有其他的方法。OP problem的实际问题是它构建Sql Query

select * from mytable where colours=red  # Check the missing quotation around text red

您希望迭代t中的元素。因此,您不需要[]周围的x

import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx", db="world")
cursor = db.cursor()
t=['red', 'yellow']

for x in t:
    cursor.execute("select * from mytable where colours=%s", x)

相关问题 更多 >