DBにある任意のテーブルの内容を表示するツールは、DBを使ったシステム開発を経験された方は使ったことがあると思います。
そのようなツールを実装するには、テーブルの名前や含まれるカラムの名前といった通常のクエリーでは取得することができない情報を取得する必要があります。
PostgreSQLやOracleではシステムカタログという、テーブルの構造などを格納するDBシステムの内部テーブルにアクセスして、そのような情報を取得することができます。
pythonのsqlite3でそのような動作をさせたくて調べた結果をメモします。
結論からいえばテーブル名を取得できるような仕組みはおそらくなさそうsqlite_masterというテーブルにアクセスすればできそう(ちゃんと調べたらありました。別途記事にします…)で、テーブルのカラム名を取得する方法はいくつかあるようです。
1つはhttp://www.sqlite.org/pragma.htmlにあるように、
PRAGMA table_info(table-name);
を使ってテーブルのカタログ情報から取得するやりかたと、
http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.description
のcursor.descriptionを使うやり方があります。
前者は次のように使えます。
C:\Users\oaka>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> con = sqlite3.connect("dummy.db") >>> con.executescript("""create table my_tbl(a integer, b integer);""") <sqlite3.Cursor object at 0x01A36860> >>> cur = con.cursor() >>> cur.execute("PRAGMA table_info(my_tbl)") <sqlite3.Cursor object at 0x01A36830> >>> print cur.fetchall() [(0, u'a', u'integer', 0, None, 0), (1, u'b', u'integer', 0, None, 0)] >>>
後者についてはテーブルを表示&編集するCGIを作ってみましたのでご参考まで。
抜粋
cur = con.cursor() try: cur.execute("select * from %s" % tableName) except: cur.close() cur = None print '<th>ColumnName</th>' desc = None if cur != None: desc = cur.description for columnIndex in range(0,6): columnName = '' if desc != None: if columnIndex < len(desc): columnName = desc[columnIndex][0] print '<th><input type="text" name="columnName%d" size="10" value="%s"></th>' % (columnIndex,columnName) print '</tr>'
実行イメージ