Sitemap
Roshberry Digital

Sharing Ideas, Concepts and Thoughts

Connecting to SQL Server Database using Python

2 min readMar 12, 2020

--

Press enter or click to view image in full size
Photo by Chris Ried on Unsplash

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.

Visual Studio Community 2017

Python 3.8.2

Microsoft SQL Server Express

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

  1. Launch SQL Server Management Studio — Run as an administrator.
  2. Right-click on Databases and select New Database. Create a sample database in SQL Server (As an Admin user)
  3. 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

  1. Launch Visual Studio and create a simple Python application. (As an Admin user)
  2. Make sure you have set the python environment for the application.
  3. Use this sample code to test database connection in Python app:
Press enter or click to view image in full size

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:

  1. From Solution Explorer → select the python file you want to execute.
  2. Right-click and select Start without Debugging option.
  3. You can see the results in the command prompt window.
Press enter or click to view image in full size

Related posts:

Connecting to Oracle Database using IronPython

Connecting to SQL Server using IronPython

--

--

Written by Velammal Ayyappan

Android Developer | Interested in Mobile Technologies and Hybrid Programming.