I need a way to fetch similar records from DB using LIKE from Django . My code is :
def fetchProductsDate1(request):
query = request.session.get('query')
date1 = request.session.get('date1')
db = pymysql.connect(host=host,user=user,passwd=passwd,db=dbName)
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
stmt = "SELECT FSN FROM tab WHERE query LIKE '%s' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)
log.info(stmt)
cur.execute(stmt)
rows = cur.fetchall()
json_data = rows[0][0]
The db statement looks like:
SELECT num FROM tab WHERE query LIKE 'soch sarees' AND DATE(updated_at) LIKE '2018-11-14'
I want the statement to be like :
SELECT num FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'
Any help will be really nice :)
Thanks.
You can use %%
to do that
stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%s%%' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)
Which will give us
SELECT FSN FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'
Also, I think it' a bad practice to concat parameters like this.This opens path to SQL Injection
You could try:
select_stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%(name)%%%' AND DATE(updated_at) LIKE '%(date)%'"
cursor.execute(select_stmt, { 'name': 'soch sarees','date':'2018-11-14' })
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.