Files
mssql-interactions-python/other_queries_tsql.py
T
2026-02-16 15:12:09 +00:00

59 lines
1.2 KiB
Python

import pyodbc
try:
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes')
cursor = connection.cursor()
# wuery 1
print("counting all records in table...")
cursor.execute("select count(*) as total_records from tblCustomers")
while 1:
row = cursor.fetchone()
if not row:
break
print(row.total_records)
print("--- next query ----")
# query 2
print("fetching server name...")
cursor.execute("select @@SERVERNAME as server_name")
while 1:
row = cursor.fetchone()
if not row:
break
print(row.server_name)
print("--- next query ----")
# query 3
print("some DMV stuff...")
cursor.execute("select top 10 wait_type, wait_time_ms from sys.dm_os_wait_stats where wait_time_ms > 5 order by wait_time_ms desc")
while 1:
row = cursor.fetchone()
if not row:
break
print(row.wait_type, row.wait_time_ms)
print("--- no more queries ... ----")
cursor.close()
connection.close()
except pyodbc.Error as ex:
print()
print("exception: ",ex)
cursor.close()
connection.close()
print()
exit()
print()