【发布时间】:2015-12-27 11:50:13
【问题描述】:
我需要使用 MySQLdb 从 Python 脚本运行一系列 SQL 选择语句。我想传递给 select 语句的变量之一是 unit_ids。我尝试将unit_ids 视为一个字符串以及一个字符串元组。最初,反斜杠被插入到字符串中。在网上查看后,我已经能够避免反斜杠,但现在正在插入额外的引号。这是我当前的代码:
connection = MySQLdb.connect('localhost', 'root', '*****', 'test')
cur = connection.cursor
unit_ids = ('0A1', '0A2', '0A3', '0A4')
attr = 'sample'
cur.execute("""SELECT COUNT(*) FROM test WHERE attribute = %s AND unit_id IN %r""", (a, tuple(unit_ids)))
使用cur._last_executed,我可以看到实际执行的SQL语句是:
SELECT COUNT(*) FROM test WHERE attribute = 'sample' AND unit_id IN ("'0A1'", "'0A2'", "'0A3'", "'0A4'")
关于我需要更改什么以使('0A1', '0A2', '0A3', '0A4') 在 SQL 语句中保持不变有什么想法吗?
更新:这是我使用 %s 时得到的确切输出:
>>> cn = MySQLdb.connect('localhost', 'root', '***', '***')
>>> c = cn.cursor()
>>> unit_ids = ('0A1', '0A2', '0A3', '0A4')
>>> a = 'foo'
>>> c.execute("""select count(*) from model_test where attribute = %s and unit_id in %s""", (a, unit_ids))
1L
>>> print(c._last_executed)
select count(*) from model_test where attribute = 'foo' and unit_id in ("'0A1'", "'0A2'", "'0A3'", "'0A4'")
此时,我想我可能只需要为unit_ids 的每个元素(例如unit_id1 = '0A1')创建单独的变量。顺便说一句,我使用的是 Python 2.7.9 和 MySQL Server 5.6。
更新 2:@thebjorn 解决了它:我的 MySQLdb 版本已过时。升级后,SQL 语句中不再插入多余的引号。
【问题讨论】:
-
或许可以试试:
unit_ids = '("0A1", "0A2", "0A3", "0A4")' -
这很有趣。
print("""SELECT COUNT(*) FROM test WHERE attribute = %s AND unit_id IN %r""", (a, tuple(unit_ids)))适合我,cur.execute应该符合相同的语法。 -
或添加尾随逗号并在执行字符串中仅使用 unit_ids 而不是 tuple(unit_ids)
标签: python mysql mysql-python