Connect MS SQL Server 2012 With Python 3.5

Introduction

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

Basic Configuration Required

  1. Python 3.5.2 should be installed and set 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 name of "test" and Save it to E:\ drive.
  3. open Command Prompt
  4. Install Ms SQL Server package for Python by using 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 package for MS SQL so you can import it into class file like below.
    1. import pymssql  

Complete Code for Database connection from Python with MS SQL Server

Below code will do MS SQL Server database connection  with Python.
  1. import pymssql  
  2.   
  3. class PythonDbConnect:  
  4.  def __init__(self, name):  
  5.   self.name = name  
  6.   
  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()  
  16.   
  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>
 
Example
  1. python test  
Output
 
 

Conclusion

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