MicrosoctCprog
MicrosoctCprog

Reputation: 490

How to print rows with pyodbc

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=server_name;"
                      "Database=db_name;"
                      "Trusted_Connection=yes;")


cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))

I got output

<pyodbc.Cursor object at 0xXXXXXXXXXXXXXXX>
<pyodbc.Cursor object at 0xXXXXXXXXXXXXXXX>
<pyodbc.Cursor object at 0xXXXXXXXXXXXXXXX>
<pyodbc.Cursor object at 0xXXXXXXXXXXXXXXX>
<pyodbc.Cursor object at 0xXXXXXXXXXXXXXXX>

Why I can't see the text?

And when I want to print how many rows return with

print(len(cursor.execute('SELECT * FROM Table')))

I got error

TypeError: object of type 'pyodbc.Cursor' has no len()
  1. How can I print rows?
  2. How can I print how many rows return?

Upvotes: 0

Views: 1998

Answers (1)

Synthaze
Synthaze

Reputation: 6090

rows = cursor.fetchall()

for row in rows:
    print (row)

cursor is an object which does not behave as a list. So you can't go through as you do with a list.

To make a list from the cursor, use fetchall() method.

Upvotes: 2

Related Questions