To connect to a Microsoft SQL Server database from Python, you can use pyodbc, a Python ODBC database adapter. Here's an example of how to use pyodbc to connect to a SQL Server database:
import pyodbc
# Replace with your server name, username, and password
server = 'your_server_name'
username = 'your_username'
password = 'your_password'
# Set up the connection
cnn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';UID=' + username + ';PWD=' + password)
# Create a cursor
cursor = cnn.cursor()
# Execute a query
cursor.execute('SELECT * FROM your_table')
# Iterate over the results
for row in cursor:
print(row)
Be sure to replace
your_server_name
, your_username
, your_password
, and your_table
with the correct values for your database. Also, note that you may need to install the ODBC driver for SQL Server on your system if you don't already have it.
Comments
Post a Comment