Introduction
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
- Python 3.5.2 should be installed and set the global environment variable.
- Login to MS SQL Server with SQL Server Authentication
Python Code Development
- Open Sublime Text.
- Create one file with the name of "test" and Save it to E:\ drive.
- open Command Prompt
- Install the MSSQL Server package for Python by using the below command.
- Also, don't forget to upgrade MS SQL Server Driver for Python like below.
- Upgrade Ms SQL Server Driver
- It will install a package for MS SQL so you can import it into a class file like below.
Complete Code for Database connection from Python with MS SQL Server
The 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 the MSSQL Server. It is very easy but it should be installed. Also, fetching data from MS SQL Server by Python is very fast.