2013-08-17 195 views
1

我想從MySQL中選擇值如下在WHERE子句

do_not_select = [1,2,3] 

cursor = database.cursor() 
cursor.executemany("""SELECT * FROM table_a WHERE id != %s""",(do_not_select)) 
data = cursor.fetchall() 

查詢Python的MySQL的executemany返回在數據庫中的所有值分開形成的第一個ID(1)。但我不想讓它選擇ID 1,2或3。

這是可能的使用executemany命令..?

回答

1

NOT IN一展身手:

do_not_select = [1, 2, 3] 

cursor.execute("""SELECT * FROM table_a 
        WHERE id NOT IN ({}, {}, {})""".format(do_not_select[0], 
                  do_not_select[1], 
                  do_not_select[2])) 
data.cursor.fetchall() 

我懷疑(雖然我沒有測試過這一點),這將更好地工作ID do_not_select是一個元組,那麼我想可以只火了直入查詢:

do_not_select = (1, 2, 3) 
cursor.execute("""SELECT * FROM table_a 
        WHERE id NOT IN {}""".format(do_not_select)) 
data.cursor.fetchall() 

我很想知道,如果這個工程 - 如果你嘗試它,請讓我知道:)

+0

這工作我f我輸入它們,但是如果我使用我的do_not_select列表餵食它們, – Jim

+0

你需要解壓do_not_select到條件,我會更新 –

+0

以上是的,.format的作品!非常感謝 :-) – Jim