私は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がその変数をタプルとして受け取るためだと理解しました。
しかし、2番目のクエリでは、(mes_sql,estacio)
それが機能するために角かっこなしで書く必要があります。角かっこで囲むと
sqlite3.InterfaceError:パラメータ1のバインド中にエラーが発生しました-おそらくサポートされていないタイプです。
なぜそれが起こっているのですか?私はtry-errorによってこの問題を解決しましたが、なぜそのようにする必要があるのか知りたいのです。