Python pyodbc.row to list

13,414

I believe you need to use cert_data directly and not cert_list. Try below. Usually cursor.fetchone() retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. Are you using pyodbc?

cert_data = cursor.fetchone()
print type(cert_data) 

Instead of using cursor.fetchone(), you could also use the cursor as an iterator

for row in cursor:
   print row
   # use row data to insert to mongodb

Updating answer as per comments. To convert pyodbc.row to list you could use simple list comprehension.

for row in cursor:
   row_to_list = [elem for elem in row]
Share:
13,414
Heath
Author by

Heath

A water resources Engineer who likes to develop new software applications for use by clients and for other exciting projects. Mostly uses Javascript and python, but always looking to expand.

Updated on June 15, 2022

Comments

  • Heath
    Heath almost 2 years

    I am trying to create a python script to convert from SQLServer database to Mongodb. In the query from SQLServer, I am returning the data as JSON using the FOR JSON AUTO method. When I use the following code, I cannot get the right type for my var for pymongo to insert the data correctly.

    client = MongoClient('localhost', 27017)
    db = client.npnrd_test
    collection = db.certs
    
    sql_file = open('./sql/F1043_Tract.sql')
    sql_d = sql_file.read()
    sql_file.close()
    
    cursor.execute(sql_d)
    cert_data = cursor.fetchone()
    cert_list = cert_data[0]
    print(cert_list)
    print(type(cert_list))
    

    When I get the "type" of cert_list it is a class 'str' not class list as it should be for pymongo. If I print the data and copy and paste it directly into a new variable, it is a type class list and completes in pymongo. What am I missing?

  • Heath
    Heath over 5 years
    Yeah, sorry I forgot to mention that I am using pyodbc. The type of "cert_data" is a pyodbc.Row not a list as I need. When I iterate through the cursor, it's the same pyodbc.Row as the others. Thanks for the help.