Menu

How can i acess other rows of a table

Help
Zach
2009-09-23
2012-09-19
  • Zach

    Zach - 2009-09-23

    Ok I have the following code so far:

    import MySQLdb

    conn = MySQLdb.connect( host = "localhost",user =
    "username",passwd = "myPw",db =
    "myDB",unix_socket='/opt/lampp/var/mysql/mysql.sock')

    cursor = conn.cursor ()

    cursor.execute ("SELECT * FROM Contacts")

    result = cursor.fetchone()

    print "Hey,", result, result

    cursor.close ()

    conn.close ()

    and so it connects to the server and it is supposed to print out a first name
    and last name of someone on the contact list. But right now i only know how to
    access the most recently added contact. How can i access additional rows?
    Thanks for any help I hope you understand!

     
  • Kyle VanderBeek

    Kyle VanderBeek - 2009-09-23

    The default cursor can be used as an iterator:

    for row in cursor:

    print "Hey,", row, row

    Or you can just call fetchone() repeatedly (in a loop) to fetch a row at a
    time. It'll return None when the results are exhausted

    while True:

    row = cursor.fetchone()

    if row is None:

    break

    print "Hey,", row, row

    Or, you can use fetchall() to grab them all at once:

    rows = cursor.fetchall()

    for row in rows:

    print "Hey,", row, row

     
  • Zach

    Zach - 2009-09-23

    THanks so much for the help it worked!

     

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.