Django MySql原始查询错误参数索引超出范围

2024-03-28 20:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

此视图在Windows上的纯pyton/Django/mysql上运行良好
我将这个移植到jython/Django/mysql上,它会给出错误-

Exception received is : error setting index [10] [SQLCode: 0]    
Parameter index out of range (10 > number of parameters, which is 0). [SQLCode: 0],  
[SQLState: S1009]

查询是-

^{pr2}$

如您所见,有10个参数被传递给这个查询。 错误是否意味着查询没有获取参数?在

我已经在执行之前打印出了参数,它们显示为正确传递-

1 - Start Parameters being passed are : 1 11 2010 10 0   
2 - End Parameters being passed are : 1 11 2010 10 5

在第二种环境中,唯一不同的是没有可用于此日期范围的数据。但这个错误似乎与数据无关。在

任何想法都是值得赞赏的。在


Tags: of数据django视图参数indexiswindows
2条回答

您确定参数标记是%s而不是?甚至是:parameter?请检查DB-API模块的^{}参数以找出答案。在

这确实是一个参数样式问题。你要用吗?而不是%s

以下是如何重现所得到的错误:

shell> jython
>>> from com.ziclix.python.sql import zxJDBC
>>> (d, v) = "jdbc:mysql://localhost/test", "org.gjt.mm.mysql.Driver"
>>> cnx = zxJDBC.connect(d, None, None, v)
>>> cur = cnx.cursor()
>>> cur.execute("SELECT %s", ('ham',))
..
zxJDBC.Error: error setting index [1] [SQLCode: 0]
Parameter index out of range (1 > number of parameters,
  which is 0). [SQLCode: 0], [SQLState: S1009]

现在,如果你用引号括起来?-马克,你会遇到同样的问题:

^{pr2}$

关键是不要使用引号,而是让数据库接口为您完成:

>>> cur.execute("SELECT ?", ('ham',))  
>>> cur.fetchall()
[(u'ham',)]

下面是我如何在代码中做到这一点。首先,将要用于str_to_date()函数的字符串如下:

start = "%d,%d,%d,%d,%d" % (int(tempStart.month),
  int(tempStart.day), int(tempStart.year),int(tempStart.hour), 
  int(tempStart.minute))
stop = "%d,%d,%d,%d,%d" % (int(tempEnd.month),
  int(tempEnd.day), int(tempEnd.year), int(tempEnd.hour),
  int(tempEnd.minute))

创建SELECT语句,但不使用任何引号,并将其传递给光标。数据库接口将为您完成这项工作。另外,我们将“粒度”值作为参数。在

select = """SELECT value FROM table_name
  WHERE value_till_dt >= str_to_date(?, '%%m,%%d,%%Y,%%H,%%i')
  AND value_till_dt <= str_to_date(?, '%%m,%%d,%%Y,%%H,%%i')
  AND granularity=?
  ORDER BY value_till_dt
"""
cursor.execute(select, (start,stop,5))

我希望这有帮助!在

相关问题 更多 >