Convert sql result to list python

后端 未结 5 672
醉话见心
醉话见心 2021-02-05 19:17

im beginner with python.I want to convert sql results to a list.Here\'s my code:

cursor = connnect_db()

query = \"SELECT * FROM `tbl`\"

cursor.execute(query)

         


        
5条回答
  •  隐瞒了意图╮
    2021-02-05 19:42

    When I used the answer from Sudhakar Ayyar, the result was a list of lists, as opposed to the list of tuples created by .fetchall(). This was still not what I wanted. With a small change to his code, i was able to get a simple list with all the data from the SQL query:

    cursor = connnect_db()
    
    query = "SELECT * FROM `tbl`"
    
    cursor.execute(query)
    
    result = cursor.fetchall() //result = (1,2,3,) or  result =((1,3),(4,5),)
    
    final_result = [i[0] for i in result]
    

    Additionally, the last two lines can be combined into:

    final_result = [i[0] for i in cursor.fetchall()]
    

提交回复
热议问题