Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data with pymysql (DictCursor)

Tags:

python

pymysql

It seems like a really simple task but I'm having difficulties doing it proper.

My SQL Query look like this:

self.link = self.db.cursor(pymysql.cursors.DictCursor);
self.link.execute("SELECT * FROM crawler_data WHERE id=%d" % id_crawl)

And I want to access the columns by the following:

row = self.link.fetchall()
if row["address"]:
    self.address = self.filterAddress(row["address"])

I get the error "list indices must be integers, not str".

When I print the row I get the following structure returned:

{u'address': 'Address Value', u'domain': 'Domain Value'}

How do I access the "address" string?

like image 527
Marcus Lind Avatar asked Apr 18 '14 09:04

Marcus Lind


2 Answers

In the case above I was trying to select only 1 result (WHERE id=:%d), and then check if it had address set. To do this, it is not a good idea to use self.link.fetchall() because that returns a list with all results that can be used in a loop for example.

The correct function to use is self.link.fetchone() which only return the dictionary. If you use:

row = self.link.fetchone()

then you can also use

print row["key"]

If you use

row = self.link.fetchall()

then you have to use

print row[0]["key"]
like image 87
Marcus Lind Avatar answered Sep 29 '22 11:09

Marcus Lind


The results of the fetchall() will be a list of dictionairies. In your example, access the string by

results = self.link.fetchall()
row = results[0]
self.address = self.filterAddress(row["address"])
like image 20
Tim Steinkuhler Avatar answered Sep 29 '22 11:09

Tim Steinkuhler