sql query in python code example

Example 1: python query mssql

import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'   
driver= '{ODBC Driver 17 for SQL Server}'

with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
        row = cursor.fetchone()
        while row:
            print (str(row[0]) + " " + str(row[1]))
            row = cursor.fetchone()

Example 2: execut sql python

# connect database and create cursor here
import sqlite3 
conn = sqlite3.connect('File.Name')
cur = conn.cursor()
# statement to be executed
cur.execute("""SELECT COL_NAME FROM TABLE_NAME LIMIT 5;""").fetchall()

Example 3: python sql

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install 
  mysql-connector-python

Example 4: python retrieves records after db select query

cursor.fetchall()

Tags:

Sql Example