Я пытаюсь выполнить пользовательский запрос sql в django в базе данных sqlite3 и получить операционную ошибку, когда я пытаюсь передать более одного параметра в мой оператор sql. Я не уверен почему, я попытался использовать cursor.fetchall () вместо namedtuplefetchall, но это не сработало. Моя база данных называется cardholder.sqlite3, и у меня есть таблица с именами держателей карт, из которых я пытаюсь извлечь данные.
ниже приведен соответствующий код
from django.db import connections
from collections import namedtuple
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
, затем некоторые представления в между
@login_required
def databaseTest(request):
if request.method == 'POST':
postid = request.POST.get("id")
with connections['cardholders'].cursor() as cursor:
cursor.execute("SELECT * FROM %s WHERE ID = %s",['cardholders',postid])
row = namedtuplefetchall(cursor)
cursor.close()
return render(request, 'LibreBadge/databaseTest.html',
context = {"AlertMessage":AlertMessage.objects.all, "row":row})
row = "none"
else:
return render(request, 'LibreBadge/databaseTest.html',
context = {"AlertMessage":AlertMessage.objects.all})
и трассировкой
Environment:
Request Method: POST
Request URL: http://localhost:8000/databaseTest/
Django Version: 3.0.5
Python Version: 3.8.2
Installed Applications:
['LibreBadge',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
The above exception (near "?": syntax error) was the direct cause of the following exception:
File "/home/micah/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/micah/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/micah/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/micah/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/micah/Documents/GitHub/LibreBadge/mysite/LibreBadge/views/views.py", line 27, in databaseTest
cursor.execute("SELECT * FROM %s WHERE ID = %s",['cardholders',postid])
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /databaseTest/
Exception Value: near "?": syntax error