何らかの理由で、sqlite の対話型シェル コマンドに相当するものを取得する方法が見つかりません。
.tables
.dump
Python sqlite3 API を使用します。
そのようなものはありますか?
Python の場合:
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
私の他の答えに気をつけてください。パンダを使用すると、はるかに高速な方法があります。
SQLITE_MASTER テーブルにクエリを実行して、テーブルとスキーマのリストを取得できます。
sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
);
sqlite> select sql from sqlite_master where type = 'table' and name = 'job';
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
)
Python でこれを行う最も速い方法は、Pandas (バージョン 0.16 以降) を使用することです。
1 つのテーブルをダンプします。
db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')
すべてのテーブルをダンプします。
import sqlite3
import pandas as pd
def to_csv():
db = sqlite3.connect('database.db')
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
table.to_csv(table_name + '.csv', index_label='index')
cursor.close()
db.close()
私は Python API に詳しくありませんが、いつでも使用できます
SELECT * FROM sqlite_master;
これは、テーブル名とそれらのテーブルの列名を出力するための短くて簡単な python プログラムです (python 2. python 3 が続きます)。
import sqlite3
db_filename = 'database.sqlite'
newline_indent = '\n '
db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()
result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(zip(*result)[0])
print "\ntables are:"+newline_indent+newline_indent.join(table_names)
for table_name in table_names:
result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
column_names = zip(*result)[1]
print ("\ncolumn names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names))
db.close()
print "\nexiting."
(編集:これについて定期的に投票を行っているため、この回答を見つけている人向けのpython3バージョンを次に示します)
import sqlite3
db_filename = 'database.sqlite'
newline_indent = '\n '
db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()
result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(list(zip(*result))[0])
print ("\ntables are:"+newline_indent+newline_indent.join(table_names))
for table_name in table_names:
result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
column_names = list(zip(*result))[1]
print (("\ncolumn names for %s:" % table_name)
+newline_indent
+(newline_indent.join(column_names)))
db.close()
print ("\nexiting.")
どうやら Python 2.6 に含まれている sqlite3 のバージョンにはこの機能があります: http://docs.python.org/dev/library/sqlite3.html
# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os
con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
いろいろいじった後、テーブルのメタデータをリストするためのsqlite docsで、接続されたデータベースでさえも、より良い答えを見つけました。
meta = cursor.execute("PRAGMA table_info('Job')")
for r in meta:
print r
重要な情報は、my_table ではなく、table_info の前に添付ハンドル名を付けることです。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == "__main__":
import sqlite3
dbname = './db/database.db'
try:
print "INITILIZATION..."
con = sqlite3.connect(dbname)
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for tbl in tables:
print "\n######## "+tbl[0]+" ########"
cursor.execute("SELECT * FROM "+tbl[0]+";")
rows = cursor.fetchall()
for row in rows:
print row
print(cursor.fetchall())
except KeyboardInterrupt:
print "\nClean Exit By user"
finally:
print "\nFinally"
ダンプについては、こちらをご覧ください。ライブラリsqlite3にダンプ機能があるようです。