2011年2月5日土曜日

PythonでSQLite - カラムの新規追加

SQLiteのDBのテーブルにカラムを新規追加する.既にあれば何もしない.
from sqlite3 import dbapi2 as sqlite

dbname = "test.db" #DBファイルの名前
tablename = "personae" #テーブルの名前
colname = "sp" #新しく追加するカラムの名前
con = sqlite.connect(dbname)
#カラムの存在確認
cur = con.execute("PRAGMA table_info('%s')" % tablename)
res = cur.fetchall()
i = 0
while i < len(res):
    if res[i][1] == colname: break
    i += 1
if i == len(res): #存在してないので作る
    cur = con.execute("ALTER TABLE %s ADD COLUMN %s INTEGER" % (tablename,colname))
    con.commit()
con.close()

2011年2月3日木曜日

PythonでSQLite - テーブルの新規作成

SQLiteのDBにテーブルを新規作成する.既にテーブルがあれば何もしない.
from sqlite3 import dbapi2 as sqlite

dbname = "test.db" #DBファイルの名前
tablename = "personae" #テーブルの名前
con = sqlite.connect(dbname)
#テーブルの存在確認
cur = con.execute("SELECT * FROM sqlite_master WHERE type='table' and name='%s'" % tablename)
if cur.fetchone() == None: #存在してないので作る
    con.execute("CREATE TABLE %s(id INTEGER, name TEXT, hp INTEGER, mp INTEGER)" % tablename)
    con.commit()
con.close()