[英]Django : How to use LIKE while fetching data from mysql DB
I need a way to fetch similar records from DB using LIKE from Django . 我需要一种使用Django的LIKE从数据库中获取类似记录的方法。 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: db语句如下所示:
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'
从选项卡中选择FSN,在其中查询类似'%soch sarees%'和DATE(updated_at)类似'2018-11-14'
Also, I think it' a bad practice to concat parameters like this.This opens path to SQL Injection 另外,我认为连接这样的参数是一种不好的做法,这为SQL注入打开了道路
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' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.