Convert sql result to list python

后端 未结 5 689
醉话见心
醉话见心 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:26

    One needs to only call list( cursor ) as demonstrated below.

    import pymysql
    
    # Create the database connection.
    # The connection parameters are host, port, user, password, and database.
    # These parameters in this code are held in the app.config().
    dump_conn = pymysql.connect(
        host=app.config[ 'DUMP_SQLALCHEMY_HOST' ],
        port=int( app.config[ 'DUMP_SQLALCHEMY_PORT' ] ),
        user=vault[ 'data' ][ 'username' ],
        passwd=vault[ 'data' ][ 'password' ],
        db=app.config[ 'DUMP_SQLALCHEMY_DB' ]
    )
    
    # Grab the query from a sql_queries helper file.
    sql_query = query_transactions_for_csv()
    
    # From the connection get a cursor.
    dump_cursor = dump_conn.cursor()
    
    # Handle the cursor.close() with a 'with' statement.
    with dump_cursor as cursor:
    
        # Execute the query.
        cursor.execute( sql_query )
    
        # Use list( cursor ) to get a Python list.
        rows = list( cursor )
    

提交回复
热议问题