2017年7月8日土曜日

Python から SQlite3でテーブル名を変数で作りたい時

タイトルがちょっとおかしい。
要は、テーブル名を固定ではなく、変数を使って作りたい場合。

d_name='usd_jpy'
sqlite_controller.cur.execute("""create table  %s(instrument,time,openask,closeask,highask,lowask,openbid,closebid,highbid,lowbid,complete);""" % d_name)  #テーブル作成

これでテーブル作成できましたね。

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の仕様なのか……。