Thursday, September 21, 2023
HomeSoftware EngineeringRetrieve data from MSSQLServer in Python

Retrieve data from MSSQLServer in Python

The beneath Python code will create a connection to a MSSQLServer occasion, and retrieve knowledge from it again right into a variable referred to as tblResults.

# use pyodbc for database connection
import pyodbc

# maintain our database credentials in a retailer
secrets and techniques = {
    'host': '<db_host>',
    'Identify': '<db_name>',
    'username': '<db_username>',
    'password': '<db_password>',

# create a connection string
conn_str = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER=tcp:{secrets and techniques['host']};DATABASE={secrets and techniques['Name']};UID={secrets and techniques['username']};PWD={secrets and techniques['password']}"

# create a connection to the database
conn = pyodbc.join(conn_str)

# a reusable perform to get knowledge from
def sql_get(sql, conn):
    cursor = conn.cursor()
    columns = [column[0] for column in cursor.description]
    outcomes = []
    for row in cursor.fetchall():
        outcomes.append(dict(zip(columns, row)))
    return outcomes

# some variable to make use of within the SQL assertion beneath
one thing = 13

# make a database connection and return the outcomes right into a variable
tblResults = sql_get(
    f"""SELECT * FROM tblName WHERE one thing='{one thing}'"""
, conn)


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments