Connect MS SQL Server 2012 With Python 3.5


Python 3.5 is a very powerful programming language. We can connect it with MSSQL Server and fetch records from Tables to display the client-side.
I will explain step by step how to connect Python with the MSSQL Server 2012.

Basic Configuration Required

  1. Python 3.5.2 should be installed and set the global environment variable.
  2. Login to MS SQL Server with SQL Server Authentication

Python Code Development

  1. Open Sublime Text.
  2. Create one file with the name of "test" and Save it to E:\ drive.
  3. open Command Prompt
  4. Install the MSSQL Server package for Python by using the below command.
    1. pip install pymssql  
  5. Also, don't forget to upgrade MS SQL Server Driver for Python like below.
    1. Upgrade Ms SQL Server Driver  
  6. It will install a package for MS SQL so you can import it into a class file like below.
    1. import pymssql  

Complete Code for Database connection from Python with MS SQL Server

The below code will do MS SQL Server database connection with Python.
  1. import pymssql  
  3. class PythonDbConnect:  
  4.  def __init__(self, name):  
  5. = name  
  7.  def PrintRecordsFromDatabase(self):  
  8.   conn = pymssql.connect(host=r"DELL", user='gul', password='test', database='test')  
  9.   print("Connected from DB")  
  10.   cursor = conn.cursor()  
  11.   cursor.execute('SELECT * FROM mmt;')  
  12.   row = cursor.fetchone()  
  13.   while row:  
  14.     print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " "  + str(row[3]) + " " + str(row[4]))   
  15.     row = cursor.fetchone()  
  17. dbObj = PythonDbConnect("Connect MS SQL")  
  18. dbObj.PrintRecordsFromDatabase()  
In the above class PythonDbConnect, method PrintRecordsFromDatabase will connect from Ms SQL Server Database and return records from Table.
Connection string should be defined like below.
  1. conn = pymssql.connect(host=r"DELL", user='gul', password='test', database='test')    
Here server name is DELL, user name is gul, password is test and database name is test.
Below table
Now go to command prompt and execute like below.
E:\python <filename>
  1. python test  


Python provides pymssql package for the connection from Python to the MSSQL Server. It is very easy but it should be installed. Also, fetching data from MS SQL Server by Python is very fast.