使用Python的SQLite查询:不同的错误

时间:2012-08-05 19:16:42

标签: python sqlite binding

我是Python新手,我正在尝试查询SQLite数据库。以下是我遇到问题的代码的一部分:

def estadistiques(estacio='all',mes='all', graph=0):

if (len(mes)<2):
    mes_sql = "0%s" %mes
else:
    mes_sql = "%s" %mes
mesos = {"1":"Gener","2":"Febrer","3":"Març","4":"Abril","5":"Maig","6":"Juny","7":"Juliol","8":"Agost","9":"Setembre","10":"Octubre","11":"Novembre","12":"Decembre"}  
if (estacio!='all'):
    if (mes!='all'):
        nom_estacio = cursor.execute("SELECT DISTINCT nom FROM estacions WHERE codi==?",[estacio]).fetchall()   

        mitjana_recarrega = cursor.execute("SELECT avg(recarrega) FROM dades WHERE strftime('%m', data)==? AND maquina IN (SELECT maquina FROM estacions WHERE codi==?)",(mes_sql, estacio)).fetchall()
        mitjana_recuperat = cursor.execute("SELECT avg(recuperat) FROM dades WHERE strftime('%m', data)==? AND maquina IN (SELECT maquina FROM estacions WHERE codi==?)",(mes_sql, estacio)).fetchall()
        mitjana_recaptat = cursor.execute("SELECT avg(recaptat) FROM dades WHERE strftime('%m', data)==? AND maquina IN (SELECT maquina FROM estacions WHERE codi==?)",(mes_sql, estacio)).fetchall()

        print "-"*50            
        print "| Dades de l'estació %s durant el mes de %s" % (nom_estacio,mesos[mes])
        print '-'*50
        print '\n\n'
        print 'Mitjana de recàrregues:\t\t %.2f' % mitjana_recarrega[0]
        print 'Mitjana de recuperacions:\t %.2f' % mitjana_recuperat[0]
        print 'Mitjana de recaptacions:\t %.2f' % mitjana_recaptat[0]

我使用raw_input获取这些参数。 第一个查询:

nom_estacio = cursor.execute("SELECT DISTINCT nom FROM estacions WHERE codi==?",[estacio]).fetchall()

如果我有[estacio],那么效果很好但是如果我用括号estacio编写它,那么Python就会抱怨。我理解这是因为SQLite将该变量作为元组。

但是在第二个查询中,我应该写(mes_sql,estacio)没有括号可以使它工作。 如果我把它放在括号之间我得

  

sqlite3.InterfaceError:错误绑定参数1 - 可能   不支持的类型。

为什么会这样?我通过try-error解决了这个问题,但我想知道为什么我应该这样做。

1 个答案:

答案 0 :(得分:1)

  

我理解这是因为SQLite将该变量视为元组。

实际上是一个序列。 (和DB-API,而不是SQLite。)恰好,列表就是一个序列。在第二种情况下,序列中的已经,因此添加括号会使其错误。

相关问题