-
Notifications
You must be signed in to change notification settings - Fork 9
Row
The Row object in the mssql-python module represents a single row of data retrieved from a SQL query. It is designed to be tuple-like, allowing you to access data using both column names and indices. This object is returned by the cursor's fetch functions, such as fetchone, fetchall, and fetchmany.
Access by Column Name: Retrieve data using the column names.
Access by Index: Retrieve data using the column indices.
Iterate Over Columns: Easily iterate over the columns in a row.
Creating a Row Object The Row object is created by the cursor when fetching data from a query. You do not need to create Row objects manually.
from mssql_python import connect
# Establish a connection
conn = connect("Server=ServerAddress;Database=myDataBase;UID=myUsername;PWD=myPassword;")
# Create a cursor object
cursor = conn.cursor()
# Execute a SQL query
cursor.execute("SELECT * FROM Employees")
# Fetch one row
row = cursor.fetchone()
You can access the data in a Row object using either the column names or the column indices.
By Column Name
Note: This will not work if the column name is an invalid Python label (e.g. contains a space or is a Python reserved word)
# Access data by column name
employee_id = row.EmployeeID
employee_name = row.EmployeeName
By Index
# Access data by index
employee_id = row[0]
employee_name = row[1]
Iterating Over Columns
You can iterate over the columns in a Row object to access all the data.
# Iterate over columns
for column in row:
print(column)
cursor_description A copy of the Cursor.description object from the Cursor that created this row. This contains the column names and data types of the columns. See Cursor.description