0

I am trying to retrieve data from mysql table using python but keep getting an error. 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

I learnt Mysql stores data as tuples, hence I would need change %s to a tuple but don't know how.

Any suggestions? thanks.

2
  • cursor.execute("select * from mytable where colours=%s",[x]) comma misplaced ? Commented May 23, 2015 at 10:01
  • @NagendraNigade, well spotted, many thanks for you good eyes. Commented May 23, 2015 at 10:06

2 Answers 2

2

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

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

select * from mytable where colours=red  # Check the missing quotation around text red
Sign up to request clarification or add additional context in comments.

7 Comments

good one, it worked. Please can you leave some explanation below. Thank you.
Can you please accept the answer and tell me where you did not get it.
I ran into a different problem and would really appreciate your suggestion. Here is what I fetched out ('red', '[1,2,3,4]'). Can you convert '[1,2,3,4]' to just a list?
I dont know if i am right but it seems you want sql query with in clause.. So if this true then you can try using select * from mytable where range in %s' % str(tuple(x['red'])) where x['red'] = [1,2,3,4] # you can use repr as well
I am not doing it for red alone, I am iterating over lots of other data.
|
0

You want to iterate over the element in t. Therefore you do not need the [] around 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)

1 Comment

thanks for the attempt, Nagendra Nigade has already spotted the error in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.