我正在尝试在PostgreSQL数据库上进行ilike查询:
conn.execute('select geocodigo, nome, GEOJSON from "Dengue_global"."Municipio" where nome' " ilike('{}%')".format(m[:4]))
其中m[:4]
是我要匹配的子字符串。
我收到以下异常:
TypeError Traceback (most recent call last)
<ipython-input-38-72ff2adae1f7> in <module>
5 except Exception:
6 print(m)
----> 7 res = conn.execute('select geocodigo, nome, GEOJSON from "Dengue_global"."Municipio" where nome' r" ilike('{}%')".format(m[:4]))
8 gj = res.fetchone()
9 if gj is None:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in execute(self, object_, *multiparams, **params)
972 """
973 if isinstance(object_, util.string_types[0]):
--> 974 return self._execute_text(object_, multiparams, params)
975 try:
976 meth = object_._execute_on_connection
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _execute_text(self, statement, multiparams, params)
1145 parameters,
1146 statement,
-> 1147 parameters,
1148 )
1149 if self._has_events or self.engine._has_events:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1238 except BaseException as e:
1239 self._handle_dbapi_exception(
-> 1240 e, statement, parameters, cursor, context
1241 )
1242
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
1458 util.raise_from_cause(sqlalchemy_exception, exc_info)
1459 else:
-> 1460 util.reraise(*exc_info)
1461
1462 finally:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in reraise(tp, value, tb, cause)
275 if value.__traceback__ is not tb:
276 raise value.with_traceback(tb)
--> 277 raise value
278
279
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1234 if not evt_handled:
1235 self.dialect.do_execute(
-> 1236 cursor, statement, parameters, context
1237 )
1238 except BaseException as e:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py in do_execute(self, cursor, statement, parameters, context)
534
535 def do_execute(self, cursor, statement, parameters, context=None):
--> 536 cursor.execute(statement, parameters)
537
538 def do_execute_no_params(self, cursor, statement, context=None):
TypeError: 'dict' object does not support indexing
如果我从查询中删除了%
符号,则该异常消失了,但我的匹配项不起作用。
有什么想法会导致这种情况,以及如何解决此问题并使我的查询有效?
===== 解决方案 =====
from sqlalchemy import text
conn.execute(atext('select geocodigo, nome, GEOJSON from "Dengue_global"."Municipio" where nome' " ilike(:search ||'%')"),
{'search': m[:4]})