Menu

Access to subitem in list

Help
2009-07-27
2012-09-19
  • Kurt Fagerburg

    Kurt Fagerburg - 2009-07-27

    I'm a newbie. Hopefully this question isn't too silly.

    I am working on a script that will select data from a MySQL database and compare values of fields within the result set. Below is my code:

    import MySQLdb

    conn = MySQLdb.connect(host = "localhost",
    user = "someuser",
    passwd = "password",
    db = "somedatabase")
    cursor = conn.cursor()
    stringSQL = "SELECT * FROM Table"
    cursor.execute(stringSQL)
    rows = cursor.fetchall()
    for item in rows[0]:
    print item
    conn.close()

    If I do something like: print rows[0] the script returns a list:
    ('Lastname', 'Firstname', 'title', 'address1', 'City', 'state', 'zip','phone')

    The way I have the script written above it returns this:
    Lastname
    Firstname
    title
    address1
    City
    state
    zip
    phone

    My problem is that I can't figure out how to access a subitem. I'd like to access only the Lastname, for example. But if I try something like this: print item[0]

    I get:

    Traceback (most recent call last):
    File "/home/kfagerb/Sandbox/mysqlTestScript.py", line 12, in <module>
    print item[0]
    IndexError: string index out of range

    And: print item(0) gives me:

    Traceback (most recent call last):
    File "/home/kfagerb/Sandbox/mysqlTestScript.py", line 12, in <module>
    print item(0)
    TypeError: 'str' object is not callable

    Can someone point me in the right direction here?

     
    • Leo Hourvitz

      Leo Hourvitz - 2009-07-27

      In general, this is all Python stuff, not MySQL-related.

      It's the fact that you're taking rows[0] that burns you. cursor.fetchall() returns a list of lists of values, so rows[0] is a single row, which is a list of values, so item is indeed only a single value, and thus you can't easily subscript it. You want something like the following.
      for row in rows:
      for item in row:
      print item

      Personally I find the above "for singular in plural:" construct to be a great aid to keeping track of what you're iterating through in Python.

      More realistically, the for statement you really want is probably something like:

      for (last,first,title,addr,city,state,zip, phone) in rows:
      print "Hello %s %s from %s, %s!"%(first,last,city,state)

      Your attempt to do item(0) is wrong because in Python, list subscripts are done with square brackets []. Parenthesis () are for invoking functions.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.