Search code examples
pythondatabasesqlitekml

Why am I getting this error IndexError: tuple index out of range


I'm trying to pull rows from a database. It pulls the first two rows however will not pull out rows 6 and 7, and it's saying this error: tuple index out of range.

db = sqlite3.connect('da_destination_history')
cursor = db.cursor()
cursor.execute('''SELECT time, dest_lat, dest_lng, source_lat, source_lng FROM destination_history''')
rows = cursor.fetchall()

for row in rows:
    print('{0} : {1}, {2}'.format(row[0], float(row[1])/1000000, float(row[2])/1000000))
    print('{0} : {6}, {7}'.format(row[0], float(row[6])/1000000, float(row[7])/1000000))
    ttime = row[0]
    dlong = float(row[1])/1000000
    dlat = float(row[2])/1000000

kml = simplekml.Kml()
kml.newpoint(name="andriod2", coords=[((float(row[2])/1000000),(float(row[1])/1000000))])
kml.newpoint(name="andriod", coords=[((float(row[7])/1000000),(float(row[6])/1000000))])
kml.save("andriod.kml")

Solution

  • As Martijn indicated the indexing of row[6] looks suspicious as you only select 5 columns.

    There is also a problem with this format function on the string:

    '{0} : {6}, {7}'.format(row[0], float(row[6])/1000000, float(row[7])/1000000)
    

    as 6 and 7 between {} indicate the argument to format() and you provide only 3 arguments (indexed with {0}, {1} resp. {2}

    If you copied this code from some example with more columns selected, you should make sure you update all indices, both in row, as well as in the format instructions.