SQLiteの使い方メモ
投稿日: 2013/03/04 カテゴリー: メモ, programing, python, 全投稿 | Tags: データベース, メモ, programing, python, sql, sqlite コメントするSQLiteはMySQLなんかよりもお手軽に使えるRDBMS。
一つのデータベースがひとつのファイルとして保存されるのでお手軽。
その半面、サーバークライアント型じゃないから複数のユーザーから同時書き込みが起こるとエラーが出る。
アプリケーションとかの中で使われるRDB。
ターミナル上で
sqlite3 DBname
と打つとDBnameに接続した状態でSQLiteが起動する。
DBnameが存在しない場合にはカレントフォルダデータベースファイルが新しく作成される。
#テーブルの作成 #testというテーブルを作成 #テキスト型のname、整数型のnum、浮動小数点型のpriceカラムを設定 create table test(name text, num integer, price real); #データベース上のテーブルを確認 .table #データベース情報を確認 .databases #データの挿入 insert into test values("apple", 10, 10.05); insert into test values("orange", 4, 8.25); insert into test values("banana", 1, 1); #同一データも挿入できる insert into test values("banana", 1, 1); insert into test values("banana", 1, 1); insert into test values("banana", 1, 1); #全レコードを選択 select * from test; #nameカラムを選択 select name from test; #priceが5よりも高いレコードを選択 select * from test where price>5; #データ更新 update test set name="BANANAS" where name=="banana"; #データ削除 delete from test where name=="orange"; #重複データを全て削除 #重複データを除いたtempテーブルを作成した後、testテーブルと入れ替える create table temp as select * from test group by name, num, price; drop table test; alter table temp rename to test; #全データ削除 delete from test; #テーブル削除 drop table test; #データベース削除 #finderとかで作成されたデータベースファイルを削除する
pythonでsqliteを使うには、
import sqlite3 #データベース接続 con = sqlite3.connect("dbname"); c = con.cursor() #SQL文の実行 c.excecute("select * from test") #insertなどの時には文字列フォーマットは使わない #SQL文中の?変数にexcecuteの第2変数が展開されて順に入れられる c.excecute(insert into test values(?,?,?), ("blueberry", 100, 6.75)) #終了処理 #最後にかならずコミットしないと変更が保存されない con.commit() c.close()
*参考*
http://docs.python.jp/2.6/library/sqlite3.html
http://ma-bank.com/item/600