# Django using cursor.execute for SQL WHERE LIKE querying

**URL:** <https://forum.djangoproject.com/t/django-using-cursor-execute-for-sql-where-like-querying/1443>\
**Category:** Using Django\
**Created:** [March 11, 2020, 6:28am UTC](https://forum.djangoproject.com/t/django-using-cursor-execute-for-sql-where-like-querying/1443 "2020-03-11T06:28:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![S-Abhishek](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/s-abhishek/32/1455_2.png) [@S-Abhishek](https://forum.djangoproject.com/u/S-Abhishek)\
**Post date:** [March 11, 2020, 6:28am UTC](https://forum.djangoproject.com/t/django-using-cursor-execute-for-sql-where-like-querying/1443/1 "2020-03-11T06:28:34Z")

</div>

Hi,

I wanted to query the database whose model doesn’t exist, so I had to use .execute,

I am relatively new to this and I just want to know if this query can cause SQL injection in any way (WHERE LIKE query)

Addition of %% around %s wont work since % has to occur inside the string which makes it difficult, So I made this query

cursor.execute(“SELECT \* from api\_user WHERE mobile\_no LIKE %s”, [’%’ + search + ‘%’])

Where search is a string variable obtained as query parameter

---

<div class="post-metadata">

**Author:** ![adamchainz](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/adamchainz/32/26_2.png) [@adamchainz](https://forum.djangoproject.com/u/adamchainz)\
**Post date:** [March 11, 2020, 7:23am UTC](https://forum.djangoproject.com/t/django-using-cursor-execute-for-sql-where-like-querying/1443/2 "2020-03-11T07:23:55Z")

</div>

That is the correct of forming this query without SQL injection possibility. The use of `'%'` in params is safe.

A separate issue: `SELECT *` is a bit fragile since the database may change the order of the columns it returns after some migrations. It’s better to explicitly name the columns you want.

That said - you _can_ use Django models to query arbitrary tables. See the `inspectdb` command and using a model with `Meta.managed = False`.

---

<div class="post-metadata">

**Author:** ![S-Abhishek](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/s-abhishek/32/1455_2.png) [@S-Abhishek](https://forum.djangoproject.com/u/S-Abhishek)\
**Post date:** [March 11, 2020, 7:27am UTC](https://forum.djangoproject.com/t/django-using-cursor-execute-for-sql-where-like-querying/1443/3 "2020-03-11T07:27:15Z")

</div>

Thank you so much for resolving the issue and pointing out the alternative, will look into `inspectdb` command

Edit: Inspectdb method is a way better alternative, thank you for pointing it out
