Connecting to SQL Server Database using Python
You can use Python script to fetch data from SQL Server database.
This post will be useful to the beginners who want to work in Python and SQL Server.
Using Python script, you can manage your data between systems.
Below are the prerequisites to start the process.
You must have to download and install the below software in your system.
Microsoft ODBC driver for SQL Server
Once Python is installed, open cmd.exe and move to Python -> Scripts folder and run this below command to install ODBC into it.
Get Velammal Ayyappan’s stories in your inbox
Join Medium for free to get updates from this writer.
pip install pyodbc
Sample database creation
- Launch SQL Server Management Studio — Run as an administrator.
- Right-click on Databases and select New Database. Create a sample database in SQL Server (As an Admin user)
- From Tables in the newly created database and Right-click and select New Table. Create a sample table and add some data in it.
Simple Python application with database connection
- Launch Visual Studio and create a simple Python application. (As an Admin user)
- Make sure you have set the python environment for the application.
- Use this sample code to test database connection in Python app:
import pyodbc
conn = pyodbc.connect(‘Driver={SQL Server};Server=SERVER_NAME;Database=TestDb;Trusted_Connection=yes;’)
cursor = conn.cursor()
cursor.execute(‘select * from TestDb.dbo.Person’)
for row in cursor:
print(row)
To run the application:
- From Solution Explorer → select the python file you want to execute.
- Right-click and select Start without Debugging option.
- You can see the results in the command prompt window.
Related posts:











