Cursor のインスタンスはには以下の属性とメソッドがあります:
| sql, [parameters]) |
まず最初の例は qmark スタイルのパラメータを使った書き方を示します:
import sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=? and age=?", (who, age))
print cur.fetchone()
次の例は named スタイルの使い方です:
import sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
{"who": who, "age": age})
print cur.fetchone()
execute() は一つの SQL 文しか実行しません。二つ以上の文を実行 しようとすると、Warning を発生させます。複数の SQL 文を一つの呼び出し で実行したい場合は executescript() を使ってください。
| sql, seq_of_parameters) |
import sqlite3
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def next(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print cur.fetchall()
もう少し短いジェネレータを使った例です:
import sqlite3
def char_generator():
import string
for c in string.letters[:26]:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print cur.fetchall()
| sql_script) |
sql_script はバイト文字列または Unicode 文字列です。
例:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(
title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
1987
);
""")
SELECT 文では、全ての行を取得し終えるまで全部で何行になったか決
められないので rowcount はいつでも None です。
DELETE 文では、条件を付けずに DELETE FROM table とすると
SQLite は rowcount を 0 と報告します。
executemany では、変更数が rowcount に合計されます。
Python DB API 仕様で求められているように、rowcount 属性は 「現在のカーソルがまだ executeXXX() を実行していない場合や、 データベースインタフェースから最後に行った操作の結果行数を 決定できない場合には、この属性は -1 となります」。
ご意見やご指摘をお寄せになりたい方は、 このドキュメントについて... をご覧ください。