Thursday, May 23, 2024

Listing records in SQL Server using Python

This is the second in the series of using Python to manipulate a SQL Server database via ODBC. This post shows how to list the contents of a table. I  created a new Python script below which imports the connection module from last week's blog post. 

It then creates a cursor object (Current Set of Records) based on the connection. Using the cursor it executes an SQL query to retrieve the contents of the table into the cursor. The pyodbc method fetchall() retrieves all the rows from the cursor and stores them into the rows list.  Next the script iterates through the rows list and prints out the tuples. We will look at filtering rows in future posts.

Python script

Below is the script we used for this week's demo. See my prior post on how to set up the ODBC connection.














Result set

The following shows the list of records retrieved (or at least the first 20 or 30):
















Next week we will look at join operations and filtering records. The python script for this week, crud_bk_s2.py, is available on our Google drive.


No comments:

Post a Comment