how to use sql select query with pyodbc and django ?

235 views
Skip to first unread message

leb dev

unread,
Sep 18, 2019, 6:36:59 AM9/18/19
to Django users
i have a django code that connect to sql server database and i am trying to select values using like but once i try it it crash and the system display the below error:

('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')

views.py
========

from django.shortcuts import render
import pyodbc
# from .models import Artist
# Create your views here.


def connect(request):
 
    conn = pyodbc.connect(
        'Driver={ODBC Driver 17 for SQL Server};'
        'Server=DESKTOP-LPD1575\\SQLEXPRESS;'
        'Database=testDB;'
        'UID=test;'
        'PWD=*****;'

    )
    query = 'jhon'
    cursor = conn.cursor()
 
    c = cursor.execute('SELECT * FROM Artist where artistName like "%?%"',query)
    print(c)
    return render (request,'connect.html',{"c":c})


connect.html
==========
<table align = "center">
<tr align="center">
            <th>id</th>
            <th>FolderNumber</th>
            <th>Folderdate</th>
           
        </tr>
{% for row in c %}
 <tr align="center">
    <td>{{ row.0 }}</td>
    <td>{{ row.1 }}</td>
    <td>{{ row.2 }}</td>
    
</tr>
{% endfor %}
</table>

Cornelis Poppema

unread,
Sep 18, 2019, 1:09:52 PM9/18/19
to Django users
I am not using pyodbc, but I imagine you should %s instead of ? as parameter marker. mysql-python actually uses python interpolation to build the query instead of simply replacing the ? signs, so pyodbc might do the same. If that's the case, it makes sense the error says there are 0 parameter markers. For reference, check the example from the docs: https://docs.djangoproject.com/en/2.2/topics/db/sql/#passing-parameters-into-raw

>>> lname = 'Doe'
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
Reply all
Reply to author
Forward
0 new messages