执行SQL IN函数

时间:2012-05-31 15:16:40

标签: python django

我有一个管理命令

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])

我可以通过输入命令名来运行它并指定参数(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时,ID将是:

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)似乎无法正常工作。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

你的代码看起来不错,但我不熟悉那些Django库。一些(可能是显而易见的)解决方法的想法:(1)构造两个不同的SQL语句来执行;在one-ID的情况下,对于one-ID情况,它是一个简单的SELECT content FROM log WHERE id =(2),使一个数组包含两个所需ID的实例,以便Django构造这个SQL:SELECT content FROM log WHERE id IN (200, 200)。换句话说,

else:
    ids.append(id)
    ids.append(id)

答案 1 :(得分:0)

您是否错过了一些括号?

SELECT content FROM log WHERE id IN 200

VS

SELECT content FROM log WHERE id IN (200)