Output pyodbc cursor results as python dictionary

后端 未结 8 1618
孤独总比滥情好
孤独总比滥情好 2020-11-29 18:37

How do I serialize pyodbc cursor output (from .fetchone, .fetchmany or .fetchall) as a Python dictionary?

I\'m using bottlepy

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 19:04

    I know this question is old, but it helped me figure out how to do what I needed, which is slightly different than what OP was asking for, so I thought I'd share, to help anyone else that needs what I needed: If you want to fully generalize a routine that performs SQL Select Queries, but you need to reference the results by an index number, not a name, you can do this with a list of lists instead of a dictionary. Each row of returned data is represented in the returned list as a list of field(column) values. The column names can be provided as the first entry of the returned list, so parsing the returned list in the calling routine can be really easy and flexible. In this way, the routine doing the database call doesn't need to know anything about the data that it's handling. Here is such a routine:

        def read_DB_Records(self, tablename, fieldlist, wherefield, wherevalue) -> list:
    
            DBfile = 'C:/DATA/MyDatabase.accdb'
            # this connection string is for Access 2007, 2010 or later .accdb files
            conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBfile)
            cursor = conn.cursor()
    
            # Build the SQL Query string using the passed-in field list:
            SQL = "SELECT "
            for i in range(0, len(fieldlist)):
                SQL = SQL + "[" + fieldlist[i] + "]"
                if i < (len(fieldlist)-1):
                    SQL = SQL + ", "
            SQL = SQL + " FROM " + tablename
    
            # Support an optional WHERE clause:
            if wherefield != "" and wherevalue != "" :
                SQL = SQL + " WHERE [" + wherefield + "] = " + "'" + wherevalue + "';"
    
            results = []    # Create the results list object
    
            cursor.execute(SQL) # Execute the Query
    
            # (Optional) Get a list of the column names returned from the query:
            columns = [column[0] for column in cursor.description]
            results.append(columns) # append the column names to the return list
    
            # Now add each row as a list of column data to the results list
            for row in cursor.fetchall():   # iterate over the cursor
                results.append(list(row))   # add the row as a list to the list of lists
    
            cursor.close()  # close the cursor
            conn.close()    # close the DB connection
    
            return results  # return the list of lists
    

提交回复
热议问题