sqlalchemy双引号列表项

时间:2015-03-22 14:54:31

标签: list sqlalchemy double-quotes where-in

使用" WHERE IN"时,我的原始查询存在引用问题。声明。 SQLAlchemy在列表中的单引号周围添加双引号...

查询我试图执行

sql_query = "SELECT col1, col2, col3 FROM preferences WHERE recipient IN :recipients"
preferences = sqlsession.execute(sql_query,dict(recipient=tuple(message.recipients))

message.recipients是这样的列表: ["收信地址""收信"" recipient3"]

SQLAlchemy调试日志

INFO:sqlalchemy.engine.base.Engine:SELECT col1,col2,col2 FROM preferences WHERE收件人IN%s
信息:sqlalchemy.engine.base.Engine :(('收件人1','收件人2','收件人3'),)

Mariadb log

9 Query     SELECT col1, col2, col3 FROM preferences WHERE recipient IN ("'recipient1'", "'recipient1'", "'recipient1'") <-- double quotes around single quotes

我已经运行strace以查看这些引用的添加位置以及它的sqlalchemy错误。

表架构:

CREATE TABLE `preferences` (
  `recipient` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `col1` tinyint(1) NOT NULL DEFAULT '1',
  `col2` tinyint(1) NOT NULL DEFAULT '1',
  `col3` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`recipient`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci

环境

CentOS 7
python-sqlalchemy.x86_64 0.9.7-3.el7 epel

1 个答案:

答案 0 :(得分:0)

您好。

根据gmane.comp.python.sqlalchemy.user的建议,您可以使用autoload功能。

总结 Michael Bayer 回答:

t = sqlalchemy.Table(
  'preferences',             # your table name
  sqlalchemy.MetaData(),
  autoload=True,
  autoload_with=sqlsession,
)

query = sqlalchemy.select([t.c.col1, t.c.col2, t.c.col3]) \
  .where(t.c.recipient.in_(message.recipients))

preferences = query.fetchall()

在我的情况下,我不得不自动加载&#34;一堆表,因为它们有复杂的连接,所以不太方便。

我结束了使用的内容:

query = "SELECT col1, col2, col3 FROM preferences\nWHERE recipient IN (%s);" % (
  ', '.join(['%s'] * len(message.recipients)
)
result = sqlsession.execute(query, (message.recipients,)) # notice the ","

我们的想法是使用将赋予IN表达式的项目数来构建查询;通过这样做,您将获得自动转义功能的好处,并与所有数据库后端兼容(据我所知)。

您可以使用以下命令查看生成的查询:

>>> print result._saved_cursor._last_executed
SELECT col1, col2, col3 FROM preferences
WHERE recipient IN ('recipient1', 'recipient2', ...);