How to Connect Python to SQL Server

There are multiple ways to connect with the SQL server using a python script.

In today's demo, I am connecting with the SQL server( installed on my local machine) with python.


Step 1. Open Jupyter notebook and install the driver for MS SQL server "pyodbc"
Details about drive are available @ "https://pypi.org/project/pyodbc/"

/*****************Code**********************/
Pip install pyodbc
/*******************************************/



Step 2. Import library "pyodbc" and setup connection using function pyodbc.connect

/*****************Code**********************/
import pyodbc
# Create connection
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=Please_Update_Actual_SQL_Server_name;'
                      'Database=AdventureWorks2012;'
                      'Trusted_Connection=yes;')
/*******************************************/





Here we are connecting with
Database: AdventureWorks2012
Authentication: Windows

Step 3. Pull the data in cursor object, In the output you can see object created

/*****************Code**********************/
cursor = conn.cursor()
cursor.execute('SELECT top 2 * FROM [AdventureWorks2012].[Person].[Address]')
/*******************************************/


We are pulling 10 rows from table "[AdventureWorks2012].[Person].[Address]"



Step 4. Print data on Jupyter screen

/*****************Code**********************/
for row in cursor:
    print(row)
/*******************************************/




Similarly, we can do other DML operations on Microsoft SQL Server databases using python scripts.

No comments:

Post a Comment