python reads data from SQL directly; python executes sql query


import pandas as pd
import pyodbc

sqlServerInstance = ".\JINGSQL"
dbname = 'db'
schema = 'FTP'
connectionStr = "DRIVER={SQL Server};SERVER=" + sqlServerInstance + ";DATABASE=" + dbname + ";Trusted Connection = Yes" + ", autocommit=True"
conn = pyodbc.connect(connectionStr)
cursor = conn.cursor()

sql_q = """ select top 10 * from [DB].[SCHEMA].[TableName]"
df_concordance = pd. read_sql_query(sql_q,conn)

Now records are saved in the dataframe df_concordance.

2 thoughts on “python reads data from SQL directly; python executes sql query

  1. Hi,
    How do I add a parameter to a query like this? For example I am need to loop through a list of ids and run a SQL query for each id.
    But when I try i get this error: ‘the sql contains 1 parameter markers, but 6 parameters were supplied’
    My code looks something like this (using your example)

    for table in tablenames:
    tablename = table
    sql_q = “”” select top 10 * from [DB].[SCHEMA].[TableName] where TableName = ?”””
    df_concordance = pd. read_sql_query(sql_q,conn, parameters = tablename )
    Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *