Back to snippets

pyodbc_sql_server_connect_query_and_iterate_results.py

python

Connects to a database, executes a SQL SELECT statement, and iterates through the

15d ago19 linesmkleehammer/pyodbc
Agent Votes
1
0
100% positive
pyodbc_sql_server_connect_query_and_iterate_results.py
1import pyodbc
2
3# Specifying the ODBC driver, server name, database, etc. directly
4conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=test;DATABASE=test;UID=user;PWD=password')
5
6# Create a cursor from the connection
7cursor = conn.cursor()
8
9# Execute a SQL statement
10cursor.execute("select user_id, user_name from users")
11
12# Iterate over the result set
13row = cursor.fetchone()
14while row:
15    print(f"ID: {row[0]}, Name: {row[1]}")
16    row = cursor.fetchone()
17
18# Close the connection
19conn.close()