Python: tuple indices must be integers, not str when selecting from mysql table

前端 未结 7 1627
梦谈多话
梦谈多话 2021-01-01 14:08

I have following method that I select all the ids from table and append them to a list and return that list. But when execute this code I end up getting tuple indicies must

7条回答
  •  长情又很酷
    2021-01-01 14:53

    To retrieve data from database use dictionary cursor

    import psycopg2
    import psycopg2.extras
    con = psycopg2.connect(database="test", user="test", password="test", host="localhost", port="5432")
    if con != None:
        print "Connection Established..!\n"
    else:
        print "Database Connection Failed..!\n"
    
    cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
    
    cur.execute("SELECT * FROM emp")
    rows = cur.fetchall()
    for row in rows:
        print "%s %s %s" % (row["id"],row["name"],row["address"])
    
    print "\nRecords Display Successfully"
    con.commit()
    con.close()
    

提交回复
热议问题