2008年2月3日日曜日

SQLite - Python

ちょっとしたデータベースを作りたくて、pythonからSQLiteを使ってみる。ライブラリリファレンスが翻訳されてないなぁ。とりあえずサンプル。

#coding: utf-8

import sqlite3

#データベースへ接続(存在していなければ作成)
con = sqlite3.connect("test.db")

#カーソルって何?
cur = con.cursor()

#本のデータを収める'book'テーブルを作成
cur.execute("""
create table if not exists booklist(
id intager not null primary key,
title text,
author text);
""")

#テーブルにデータを挿入
cur.execute("""
insert into booklist(id, title, author)
values(1, 'Python Tutorial', 'Guide van Rossum');
""")

cur.execute("""
insert into booklist(id, title, author)
values(2, 'Microeconomics', 'Paul Krugman, Robin Wells');
""")

#データを取り出す
cur.execute("select * from booklist;")
print cur.fetchall()

cur.execute("select title from booklist;")
print cur.fetchall()

cur.execute("select * from booklist where id=1;")
print cur.fetchall()

con.close()

0 件のコメント: