我有一個管理命令執行SQL IN功能
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = "[id]"
def handle(self, id, **options):
ids = []
if '-' in id:
splitted = id.split('-')
for n in range(int(splitted[0]), int(splitted[1])+1):
ids.append(n)
else:
ids.append(id)
c = connection.cursor()
c.execute('SELECT content FROM log WHERE id IN %s', [ids])
我可以通過輸入命令名稱來運行這一點,並指定paramater(ID)
當我運行command 200-205
,for循環返回一個列表:
ids =[200, 201, 202, 203, 204, 205]
而且把這個查詢:
SELECT content FROM log WHERE id IN (200, 201, 202, 203, 204, 205)
Briljant!
當我運行command 200
IDS將是:
ids = [200]
執行查詢將返回一個錯誤:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 1")
好像SELECT content FROM log WHERE id IN (200)
不工作時它應該。
我在這裏做錯了什麼?
如果我這樣做,我會得到一個錯誤:_mysql_exceptions.Warning:截斷不正確的DOUBLE值: ''200'' – nelsonvarela
沒關係......您的解決方案適合我! – nelsonvarela
你有選擇(1)或選項(2)嗎? –