Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
In this quickstart, you connect a Python script to a database that you created and loaded with sample data. You use the mssql-python driver for Python to connect to your database and perform basic operations, like reading and writing data.
The mssql-python driver doesn't require any external dependencies on Windows machines. The driver installs everything that it needs with a single pip install, allowing you to use the latest version of the driver for new scripts without breaking other scripts that you don't have time to upgrade and test.
Use the local SQL authentication example in this article only for local development against a SQL Server instance that you control. For Azure SQL Database, SQL database in Fabric, shared development environments, CI, and production deployments, start with Microsoft Entra authentication or another passwordless flow.
mssql-python documentation | mssql-python source code | Package (PyPI) | Visual Studio Code
Prerequisites
Python 3.10 or later
If you don't already have Python, install the Python runtime and pip package manager from python.org.
Don't want to use your own environment? Follow Container and local development to create a reproducible devcontainer or GitHub Codespaces environment.
Create or connect to a database on SQL Server, Azure SQL Database, or SQL database in Fabric. Use the following steps to set up a database with the AdventureWorks2025 sample schema, and keep the connection string for later.
Create a SQL database
Create or connect to a SQL database on one of the following platforms:
Setup
Follow these steps to configure your development environment to develop an application using the mssql-python Python driver.
Note
This driver uses the Tabular Data Stream (TDS) protocol. SQL Server, SQL database in Fabric, and Azure SQL Database enable TDS by default, so no extra configuration is necessary.
Install the mssql-python package
Get the mssql-python package from PyPI.
Open a command prompt in an empty directory.
Install the
mssql-pythonpackage.
Install the python-dotenv package
Get the python-dotenv package from PyPI.
In the same directory, install the
python-dotenvpackage.pip install python-dotenv
Check installed packages
You can use the PyPI command-line tool to verify that your intended packages are installed.
Check the list of installed packages with
pip list.pip list
Run the code
Create a new file
Create a new file named
app.py.Add a module docstring.
""" Connects to a SQL database using mssql-python """Import packages, including
mssql-python.from os import getenv from dotenv import load_dotenv from mssql_python import connectUse the
mssql-python.connectfunction to connect to a SQL database.load_dotenv() conn = connect(getenv("SQL_CONNECTION_STRING"))In the current directory, create a new file named
.env.Within the
.envfile, add an entry for your connection string namedSQL_CONNECTION_STRING. Use one of the following examples and replace the placeholders with your actual values.For Azure SQL Database or SQL database in Fabric, start with Microsoft Entra authentication:
SQL_CONNECTION_STRING="Server=<server_name>;Database=<database_name>;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryInteractive"For local SQL Server during development, start with SQL authentication:
SQL_CONNECTION_STRING="Server=localhost,1433;Database=<database_name>;UID=<username>;PWD=<password>;Encrypt=yes;TrustServerCertificate=yes"Caution
Treat
.envas a local development convenience, not a deployment mechanism. Never commit it, never reuse this SQL authentication sample in shared or production environments, and keep certificate validation enabled outside local development.Use Connection strings to adapt the sample for named instances, containers, or advanced settings. If you're connecting to Azure SQL Database or SQL database in Fabric, use Microsoft Entra authentication for passwordless and interactive sign-in options. For broader secret and certificate guidance, see Security best practices.
Execute a query
Use a SQL query string to execute a query and parse the results.
Create a variable for the SQL query string.
SQL_QUERY = """ SELECT TOP 5 c.CustomerID, c.CompanyName, COUNT(soh.SalesOrderID) AS OrderCount FROM SalesLT.Customer AS c LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID GROUP BY c.CustomerID, c.CompanyName ORDER BY OrderCount DESC; """Use
cursor.executeto retrieve a result set from a query against the database.cursor = conn.cursor() cursor.execute(SQL_QUERY)Note
This function essentially accepts any query and returns a result set. To iterate over the result set, use cursor.fetchone().
Use
cursor.fetchallwith aforloop to get all the records from the database. Then, print the records.records = cursor.fetchall() for r in records: print(f"{r.CustomerID}\t{r.OrderCount}\t{r.CompanyName}")Save the
app.pyfile.Tip
On macOS, both
ActiveDirectoryInteractiveandActiveDirectoryDefaultwork for Microsoft Entra authentication.ActiveDirectoryInteractiveprompts you to sign in every time you run the script. To avoid repeated sign-in prompts, sign in once through the Azure CLI by runningaz login, then useActiveDirectoryDefault, which reuses the cached credential.Open a terminal and test the application.
python app.pyHere's the expected output.
29485 1 Professional Sales and Service 29531 1 Remarkable Bike Store 29546 1 Bulk Discount Store 29568 1 Coalition Bike Company 29584 1 Futuristic Bikes
Insert a row as a transaction
Execute an INSERT statement safely and pass parameters. Passing parameters as values protects your application from SQL injection attacks.
Add an import for
randrangefrom therandomlibrary to the top ofapp.py.from random import randrangeAt the end of
app.pyadd code to generate a random product number.productNumber = randrange(1000)Tip
Generating a random product number here ensures that you can run this sample multiple times.
Create a SQL statement string.
SQL_STATEMENT = """ INSERT SalesLT.Product ( Name, ProductNumber, StandardCost, ListPrice, SellStartDate ) OUTPUT INSERTED.ProductID VALUES (%(name)s, %(product_number)s, %(standard_cost)s, %(list_price)s, CURRENT_TIMESTAMP) """Execute the statement using
cursor.execute.cursor.execute( SQL_STATEMENT, { 'name': f'Example Product {productNumber}', 'product_number': f'EXAMPLE-{productNumber}', 'standard_cost': 100, 'list_price': 200 } )Fetch the single result using
cursor.fetchone, print the result's unique identifier, and then commit the operation as a transaction usingconnection.commit.result = cursor.fetchone() print(f"Inserted Product ID : {result.ProductID}") conn.commit()Tip
Optionally, you can use
connection.rollbackto roll back the transaction.Close the cursor and connection using
cursor.closeandconnection.close.cursor.close() conn.close()Save the
app.pyfile and test the application again.python app.pyHere's the expected output.
Inserted Product ID : 1001
Next steps
Use these articles to keep building:
- Connection strings to adapt the sample for local SQL Server, Azure SQL, containers, and named instances.
- Connection management to use context managers, pooling, and connection settings.
- Troubleshooting to diagnose authentication, certificate, and connectivity problems.