简体   繁体   English

使用python从Mysql表查询和检索数据

[英]Querying and retrieving data from Mysql table using python

I am trying to retrieve data from mysql table using python but keep getting an error. 我正在尝试使用python从mysql表中检索数据,但始终出现错误。 Please see my attempt below and the data: 请在下面查看我的尝试和数据:

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])

I got the following error: TypeError: string indices must be integers, not str 我收到以下错误: TypeError: string indices must be integers, not str

I learnt Mysql stores data as tuples, hence I would need change %s to a tuple but don't know how. 我了解到Mysql将数据存储为元组,因此我需要将%s更改为元组,但不知道如何。

Any suggestions? 有什么建议么? thanks. 谢谢。

Try this and check if this resolve your problem 试试这个,检查是否可以解决您的问题

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))

Please note that here the Sql Query will build like 请注意,这里的Sql Query将像

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

Though I have not tested yet and there could be alternate way of doing this. 虽然我还没有测试过,并且可能有其他方法可以做到这一点。 The actual problem with OP problem is that it build Sql Query like 与OP问题的实际问题是,它建立Sql Query

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

You want to iterate over the element in t . 您想遍历t的元素。 Therefore you do not need the [] around x : 因此,您不需要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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM