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
- Python 3.5.2 should be installed and set global environment variable.
- Login to MS SQL Server with SQL Server Authentication
Python Code Development
- Open Sublime Text.
- Create one file with name of "test" and Save it to E:\ drive.
- open Command Prompt
- Install Ms SQL Server package for Python by using below command.
- Also, don't forget to upgrade MS SQL Server Driver for Python like below.
- Upgrade Ms SQL Server Driver
- It will install package for MS SQL so you can import it into class file like below.
Complete Code for Database connection from Python with MS SQL Server
Below code will do MS SQL Server database connection with Python.
- import pymssql
-
- class PythonDbConnect:
- def __init__(self, name):
- self.name = name
-
- def PrintRecordsFromDatabase(self):
- conn = pymssql.connect(host=r"DELL", user='gul', password='test', database='test')
- print("Connected from DB")
- cursor = conn.cursor()
- cursor.execute('SELECT * FROM mmt;')
- row = cursor.fetchone()
- while row:
- print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4]))
- row = cursor.fetchone()
-
- dbObj = PythonDbConnect("Connect MS SQL")
- 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.
- 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
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.