Search code examples
pythonsqlpython-2.7data-retrieval

Retrieve data from sql database using python


I'm a newbie for python and SQL. My database contain a field which stored path to images. I want to assign each path to a variable in python. I can only store only the path of first row. This is my code

import pymysql
from arcpy import env

env.workspace = "D:/year 4 semester 1/Python/Data/"
conn= pymysql.connect(host='localhost',user='root',password='',db='research')
cursor = conn.cursor ()

cursor.execute ("select Path from sourcedata")
data = cursor.fetchmany()
for row in data :
    a= row[0]
print a

But when I try following way including all other relevant text

for row in data :
     a= row[0]
     b = row[1]
     c = row[2]
print a

Following error appear

IndexError: tuple index out of range


Solution

  • you need to indent the print a statement to make it part of the loop. Python is very sensitive about indentation. In other languages you use braces or BEGIN END blocks, but in python you use indentation.

    The row[0], row[1] stuff refers to the elements within the retrieved row, not the different rows.

    indent the print line and it will print the first returned field, Path, for each record.

    The tuple index is out of range because there is only one field (element zero) returned.

    Your current code will iterate through every row returned and set a to each one in turn, but will only print the last value for a after it comes out of the loop.