我有一系列SQL select語句,需要使用MySQLdb從Python腳本運行。我想傳遞給select語句的變量之一是unit_ids
。我已經嘗試將unit_ids
作爲字符串以及字符串元組對待。最初,反斜槓被插入到字符串中。在網上瀏覽後,我可以避開反斜槓,但是現在插入了額外的引號。這裏是我當前的代碼:如何防止從Python插入到MySQLdb語句中的額外引號?
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而不是元組(unit_ids) – carruthd