How to use pyodbc, cursor, execute to extract data from SQL when there is no parameters for query.format?

Usually, I use the following way to extract data from SQL using python:

myConnect=pyodbc.connect('DSN=B1P HANA;UID=****;PWD=****')

query = """
        SELECT "Operator",
        FROM ******
myRow = myCursor.execute(query.format(Start1=Start1,
Result = myRow.fetchall()
OperatorTMs = pd.DataFrame(columns=["Operator", "Position"])
for i in Result:

But now, I do not need any parameters in query.format(). And I tried the way in And it does not work

So could anyone please tell mw how to do this without any parameters in query.format?

1 answer

  • answered 2019-05-15 12:03 Gord Thompson

    You really shouldn't be using .format to insert column values into your SQL command. Search for "SQL Injection" or "Little Bobby Tables" for more information.

    Instead, you should be using ? parameter placeholders and supplying the column values as additional arguments to .execute as in

    query = "SELECT col1, col2 FROM tablename WHERE col1 BETWEEN ? AND ?"
    myRow = myCursor.execute(query, Start1, End)

    For queries with no parameter values you simply pass the query string by itself

    query = "SELECT col1, col2 FROM tablename"
    myRow = myCursor.execute(query)