IT & IoT Security | Cloud | It's all about the life itself

Nothing in life is as important as you think it is, while you are thinking about it.

Python – connecting to Azure SQL Database

Hi all

In this short tutorial I’d like to cover how to connect to azure sql database , create table , insert sample data to respective columns, update data in columns and delete data with pyodbc. As an IDE I use VS code. To extract data from file I used regular experession re.findall()

import pyodbc
import re  #for regular expression
server = ''
database = 'pythonadventures'
username = 'db_user_name'
password = 'db_password'
driver= '{ODBC Driver 17 for SQL Server}'
#DB connection parameter is constructed below , according to the parameter above.
conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+password)

xfh = open("my_files/mbox.txt","r")  #This is a file handler, please use yur own file.

def createXTable(conn=conn):   #table creation
    print("Create Table process iniated")
    table_name = input("Type table name to create :")
    print("Droping existing tables"+table_name)
    cursor.execute('''DROP TABLE IF EXISTS '''+table_name+'''''')
    print("Creating hold tight :)")
    cursor.execute('create table '+table_name+' (fromX varchar(max), domainX varchar(max))')

def insertXDB(conn=conn):  #insert data
    print("Insert to table ")
    cursor = conn.cursor()
    for line in xfh:
        if not line.startswith("From:"):
        fromX=re.findall("^From: (\S+)@\S+",line)[0]
        domainX=re.findall("^From: \S+@(\S+)",line)[0]
        cursor.execute('insert or ignore into mbox (fromX,domainX) values(?,?);',(fromX,domainX))  #or ignore'u ekledim

def readXDB(conn=conn):  #read data
    print("Read from table")
    cursor = conn.cursor()
    table_name = input("Enter table name to read data :")
    cursor.execute("select top 3 fromX,domainX from "+table_name+" ") #reading top 3 row
    for i in cursor:  #reading row per row

def updateXDB(conn=conn):  #update of crud
    cursor = conn.cursor()
    #ey_to_change = input("Type F Name : ")
    #value_to_change = input("Type L Name : ")
        'update mbox set domainX = ? where fromX = ?;',
        ) #updating some data

def deleteXDB(conn=conn):  #delete some data
    cursor = conn.cursor()
    value_to_delete = input("Enter Domain value to delete :")
    cursor.execute('''delete from mbox where domainX=?;''',(value_to_delete))  #You need to enter the name of the data


The functions above can be called according to the action you want to perform.
For sure there are many different ways to perform these tasks. This is just another one.

Wish you a gr8 time.