如何在 django SQLITE 中使用原始 sql 查询执行搜索操作
How can I perform search operation using raw sql query in django SQLITE
我正在尝试在 STAT
table 的 detection
字段中搜索字符串,如下所示:
query = "select detection_class, stream_id, track_id, detection_time, " \
"frame_id" \
" FROM stats where stream_id = %s "\
"detection_class like %%s%% group by track_id; "
with connection.cursor() as cursor:
cursor.execute(query,[stream_id, detection_class])
在这里,当我给出 detection_class 中包含的单词或某些字符时,它 returns 出现这样的错误消息 TypeError('not all arguments converted during string formatting')),
。
而且,如果我尝试 detection_class=%s
它在给出 while 其他词时可以正常工作 returns None.
执行查询时不要使用字符串格式。而是使用占位符或命名参数。
query = """
SELECT detection_class,
stream_id,
track_id,
detection_time,
frame_id
FROM stats
WHERE stream_id = :stream_id
AND detection_class LIKE :dclass
GROUP BY track_id;
"""
with connection.cursor() as cursor:
params = {"stream_id": stream_id, "dclass": f"%{detection_class}%"}
cursor.execute(query, params)
我相信也可以使用占位符方法来完成,如下所示。
query = """
SELECT detection_class,
stream_id,
track_id,
detection_time,
frame_id
FROM stats
WHERE stream_id = ?
AND detection_class LIKE %?%
GROUP BY track_id;
"""
with connection.cursor() as cursor:
cursor.execute(query, (stream_id, detection_class,))
我正在尝试在 STAT
table 的 detection
字段中搜索字符串,如下所示:
query = "select detection_class, stream_id, track_id, detection_time, " \
"frame_id" \
" FROM stats where stream_id = %s "\
"detection_class like %%s%% group by track_id; "
with connection.cursor() as cursor:
cursor.execute(query,[stream_id, detection_class])
在这里,当我给出 detection_class 中包含的单词或某些字符时,它 returns 出现这样的错误消息 TypeError('not all arguments converted during string formatting')),
。
而且,如果我尝试 detection_class=%s
它在给出 while 其他词时可以正常工作 returns None.
执行查询时不要使用字符串格式。而是使用占位符或命名参数。
query = """
SELECT detection_class,
stream_id,
track_id,
detection_time,
frame_id
FROM stats
WHERE stream_id = :stream_id
AND detection_class LIKE :dclass
GROUP BY track_id;
"""
with connection.cursor() as cursor:
params = {"stream_id": stream_id, "dclass": f"%{detection_class}%"}
cursor.execute(query, params)
我相信也可以使用占位符方法来完成,如下所示。
query = """
SELECT detection_class,
stream_id,
track_id,
detection_time,
frame_id
FROM stats
WHERE stream_id = ?
AND detection_class LIKE %?%
GROUP BY track_id;
"""
with connection.cursor() as cursor:
cursor.execute(query, (stream_id, detection_class,))