python Database connections- MS SQL server connection.

Microsoft SQL Server already installed in your local machine and you need to connect with python 

using  Text editor or IDE  then this  article for you 

to connect database you need pyodbc  library.

pyodbc is an open source Python module that makes accessing ODBC databases simple. It implements the DB API 2.0 specification but is packed with even more Pythonic convenience.

The easiest way to install is to use pip: using CMD  and bellow command  it will install pyodbc

pip install pyodbc

Then using sublime or VS code or any IDE import  pyodbc library 

if your  a user then use bellow code 


import pyodbc

conn= pyodbc.connect(

        host= "DESKTOP-V5F828B\SQLEXPRESS",

        USER = "Testlogin",

        password ="1234",

        Driver='ODBC Driver 13 for SQL Server',

        Trusted_connection='no',

        PORT='1433',

        database='master'

)

mycursor =conn.cursor()

mycursor.execute("select * from INFORMATION_SCHEMA.TABLES")


for i in mycursor:

    print(i)

-----------------------------------------------------------------------------------------------------------------------------

if you are Admin then use this bellow code

import pyodbc

conn= pyodbc.connect(

        host= "DESKTOP-V5F828B\SQLEXPRESS",

        Driver='ODBC Driver 13 for SQL Server',

        Trusted_connection='YES',

        PORT='1433',

# if required use database name or directly use in sql statement ex(select * from Test.DBO.EmpDetails)

)

mycursor =conn.cursor()

mycursor.execute("select * from EmpDetails") 


for in mycursor:

    print(i)


This above code help to fetch the table data from ms sql server. for other database connections  you need to refer python documentation. IF you need to update or delete or any other changes then  create a functions in python. this data you need to display in web pages  then u need to render this data in python Django or flask. this article just explain about DB connections.


Comments