简体   繁体   English

Django:如何在从mysql DB提取数据时使用LIKE

[英]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.

相关问题 如何计算年龄是否在出生年份的范围内,同时从 Django ORM 中的 Db 获取出生年份 - How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM 如何使用 django 框架中的 sqlalchemy 在 mysql db 中插入数据? - How to insert data in mysql db using sqlalchemy from django framework? 如何将MySQL作为django项目的数据库使用? - How to use MySQL as DB for a django project? 在从mysql数据库中获取数据到python时如何编写用于检查空集的语句? - How to write statement for checking empty set while fetching data from mysql database into python? 在python中从MySql数据库中获取数据时出错 - Error while fetching data from MySql Database in python 从 django 模型中获取数据 - fetching data from django models 如何使用 django 中的 .db 文件获取数据? - How to use .db file in django for getting data? 在一定时间间隔(10秒)后使用flask从不断增加的数据库(如mysql)中获取数据 - Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask 是否可以使用javascript从Django模型数据库中获取数据? - is it possible to use javascript to get data from django models db? 从 MySQL 获取数据并从 Python 更新 - Fetching data from MySQL and updating from Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM