I’m trying to search string in the STAT
table’s detection
field like below:
JavaScript
x
8
1
query = "select detection_class, stream_id, track_id, detection_time, "
2
"frame_id"
3
" FROM stats where stream_id = %s "
4
"detection_class like %%s%% group by track_id; "
5
with connection.cursor() as cursor:
6
cursor.execute(query,[stream_id, detection_class])
7
8
Here, when I give the word or some character which are contained in detection_class, it returns an error message like thisTypeError('not all arguments converted during string formatting')),
.
and also if I try like detection_class=%s
it works properly when gives while word else it returns None.
Advertisement
Answer
Don’t use string formatting when executing queries. Instead use a placeholder OR a named parameter.
JavaScript
1
16
16
1
query = """
2
SELECT detection_class,
3
stream_id,
4
track_id,
5
detection_time,
6
frame_id
7
FROM stats
8
WHERE stream_id = :stream_id
9
AND detection_class LIKE :dclass
10
GROUP BY track_id;
11
"""
12
13
with connection.cursor() as cursor:
14
params = {"stream_id": stream_id, "dclass": f"%{detection_class}%"}
15
cursor.execute(query, params)
16
I believe it is also possible to do it using the placeholder method as well, as shown below.
JavaScript
1
15
15
1
query = """
2
SELECT detection_class,
3
stream_id,
4
track_id,
5
detection_time,
6
frame_id
7
FROM stats
8
WHERE stream_id = ?
9
AND detection_class LIKE %?%
10
GROUP BY track_id;
11
"""
12
13
with connection.cursor() as cursor:
14
cursor.execute(query, (stream_id, detection_class,))
15