List of tables, db schema, dump etc using the Python sqlite3 API
出于某种原因,我找不到一种方法来获取与sqlite的交互式shell命令等效的内容:
1 2 | .tables .dump |
使用python sqlite3 API。
有那样的吗?
在python中:
1 2 3 4 | con = sqlite3.connect('database.db') cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) |
。
注意我的另一个答案。有一种使用熊猫更快的方法。
您可以通过查询sqlite_主表来获取表和架构列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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中实现这一点的最快方法是使用熊猫(0.16及更高版本)。
转储一个表:
1 2 3 | db = sqlite3.connect('database.db') table = pd.read_sql_query("SELECT * from table_name", db) table.to_csv(table_name + '.csv', index_label='index') |
。
转储所有表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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,但您可以随时使用
1 | SELECT * FROM sqlite_master; |
显然,python 2.6中包含的sqlite3版本具有以下功能:http://docs.python.org/dev/library/sqlite3.html
1 2 3 4 5 6 7 8 | # 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 ' % line) |
这里有一个简短的python程序,可以打印出这些表的表名和列名(python 2)。接下来是python 3)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import sqlite3 db_filename = 'database.sqlite' newline_indent = ' ' 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" tables 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 (" column names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names)) db.close() print" exiting." |
(编辑:我已经定期对此进行投票,所以这里是Python3版本,供找到此答案的人使用)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import sqlite3 db_filename = 'database.sqlite' newline_indent = ' ' 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 (" tables 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 ((" column names for %s:" % table_name) +newline_indent +(newline_indent.join(column_names))) db.close() print (" exiting.") |
。
经过大量的修改,我在sqliteDocs上找到了一个更好的答案,可以列出表的元数据,甚至附加的数据库。
1 2 3 | meta = cursor.execute("PRAGMA table_info('Job')") for r in meta: print r |
关键信息是给表的信息加前缀,而不是给我的表加上附件句柄名。
看看这里有没有垃圾场。似乎库sqlite3中有一个dump函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #!/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" ######## "+tbl[0]+" ########" cursor.execute("SELECT * FROM"+tbl[0]+";") rows = cursor.fetchall() for row in rows: print row print(cursor.fetchall()) except KeyboardInterrupt: print" Clean Exit By user" finally: print" Finally" |
。
我在PHP中实现了一个sqlite表模式分析器,您可以在这里查看:https://github.com/c9s/lazyrecord/blob/master/src/lazyrecord/table parser/sqlitetabledefinitionparser.php
您可以使用此定义分析器来分析定义,如下面的代码:
1 2 | $parser = new SqliteTableDefinitionParser; $parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)'); |
。