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

前端 未结 7 1583
梦谈多话
梦谈多话 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:39

    There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names. Source

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import MySQLdb as mdb
    
    con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')
    
    with con:
    
        cur = con.cursor(mdb.cursors.DictCursor)
        cur.execute("SELECT * FROM Writers LIMIT 4")
    
        rows = cur.fetchall()
    
        for row in rows:
            print row["Id"], row["Name"]
    

提交回复
热议问题