2017年1月22日日曜日

PythonからSqlite3で検索するときにWhereで変数を使いたい

これが、ちょっと想定外の記述方法で驚きましたわ。
insertで変数を使うテクは良く見かけるけれど、whereではあまりなかったのだ。

def test(self,instruments):
    中略
    cur.execute("""select * from rate where instrument=?;""",(instruments,))
    以下略

要は、whereの条件を引数で渡してあげたかったんだ。
なんとなく?を使えば良いと感じていたんだが、

cur.execute("""select * from rate where instrument=?;""",(instruments))

とすると、

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied.

こんなエラーを吐くんだわ。

で、

cur.execute("""select * from rate where instrument=?;""",(instruments,))

にするとしれっと動く。
たぶん引数が二つ以上あったら空の,は必要なくなるんだろうな。

なんだか、よく分からない仕様だ。
Pythonの仕様なのか、Sqlite3の仕様なのか……。

0 件のコメント:

コメントを投稿