1

I tried to see if this question had been asked, which it probably has, but I couldn't find an answer. I am querying MS SQL Server from a python script using pyodbc.

I am defining a function to query SQL. The query string has both a '%R_%' which is meant as a wildcard for SQL to interpret, but also a '%s' which is meant to place a variable in python between single quotes. It looks like this:

def numcust(matter):
    QryString = """
    select count(distinct user_id)
    from dbo.tbl_case_details
    where request like '%r_%'
    and project_id in
        (
        select distinct project_id
        from dbo.tbl_projects
        where matter_number = '%s'
        );
    """ % matter
    cursor.execute(QryString)
    row = cursor.fetchone()
    return row[0]

How can I escape the wildcards for r_ so that I can successfully pass it through to SQL?

Thank you kindly.

0

2 Answers 2

2

Double the % where you want to escape them (i.e. '%%r_%%'). Also, interpolate the string in the cursor.execute function like so:

cursor.execute(QryString, matter)
Sign up to request clarification or add additional context in comments.

Comments

1

"%% %s"%("Hello",) two % signs should become one after applying the %s stuff ...

but really you should be using the built in query stuff stuff

QryString = """
select count(distinct user_id)
from dbo.tbl_case_details
where request like '%r_%'
and project_id in
    (
    select distinct project_id
    from dbo.tbl_projects
    where matter_number = '%s'
    );
"""
cursor.execute(QryString,matter) 

although you still may need to do %% for a literal %

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.