Python sqlite3 API를 사용하는 테이블, db 스키마, 덤프 등의 목록
어떤 이유로 sqlite의 대화 형 쉘 명령과 동등한 방법을 찾을 수 없습니다.
.tables
.dump
파이썬 sqlite3 API를 사용합니다.
그런 게 있습니까?
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
)
파이썬에서 :
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
내 다른 대답을 조심하십시오 . 팬더를 사용하는 훨씬 빠른 방법이 있습니다.
파이썬 에서이 작업을 수행하는 가장 빠른 방법은 Pandas (버전 0.16 이상)를 사용하는 것입니다.
하나의 테이블을 덤프하십시오.
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()
파이썬 API에 익숙하지 않지만 항상 사용할 수 있습니다
SELECT * FROM sqlite_master;
분명히 파이썬 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)
Here's a short and simple python program to print out the table names and the column names for those tables (python 2. python 3 follows).
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."
(EDIT: I have been getting periodic vote-ups on this, so here is the python3 version for people who are finding this answer)
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.")
After a lot of fiddling I found a better answer at sqlite docs for listing the metadata for the table, even attached databases.
meta = cursor.execute("PRAGMA table_info('Job')")
for r in meta:
print r
The key information is to prefix table_info, not my_table with the attachment handle name.
Check out here for dump. It seems there is a dump function in the library sqlite3.
#!/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"
I've implemented a sqlite table schema parser in PHP, you may check here: https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php
You can use this definition parser to parse the definitions like the code below:
$parser = new SqliteTableDefinitionParser;
$parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)');
'Programing' 카테고리의 다른 글
JavaScript를 트리거하는 링크를 클릭 할 때 웹 페이지가 맨 위로 스크롤되지 않도록하려면 어떻게합니까? (0) | 2020.06.28 |
---|---|
이름으로 쿠키를 삭제 하시겠습니까? (0) | 2020.06.28 |
GAC에서 어셈블리를 추출하는 방법은 무엇입니까? (0) | 2020.06.28 |
VC2010 Express에서 포함 파일 'afxres.h'를 열 수 없습니다 (0) | 2020.06.27 |
목록의 키와 기본값이 0으로 된 사전을 어떻게 만들 수 있습니까? (0) | 2020.06.27 |