简体   繁体   中英

pandas read_sql with parameters and wildcard operator

I am trying to retrieve data from sql through python with the code:

query = ("SELECT stuff FROM TABLE WHERE name like %%(this_name)s%")
result = pd.read_sql(query,con=cnx,params={'this_name':some_name})

The code above works perfectly when I don't have to pass the wildcard operator %. However, in this case the code doesn't work. How can I pass in the query the wildcard operator? Thank you.

Consider concatenating the wildcard operator, % , to passed in value:

query = ("SELECT stuff FROM TABLE WHERE name LIKE %(this_name)s") 
result = pd.read_sql(query,con=cnx, params={'this_name': '%'+ some_name +'%'})

Try using a docstring and some quotes around the like pattern. It appears you are using the pyformat paramstyle.

query = """SELECT stuff FROM TABLE WHERE name LIKE '%%(this_name)s%'"""
results = pd.read_sql(query, con=cnx, params={'this_name': some_name})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM