[英]How do I display the table structure in SQLite3 with python?
如何在python中的SQLite3中显示结构?
python 3.7
sqlite3
import sqlite3
conn = sqlite3.connect('test.db')
print ('Opened database successfully')
print ('Table created sucessfully');
conn.execute('''PRAGMA table_info('company');''')
conn.close()
'''这是你应该添加的代码
a= conn.execute("PRAGMA table_info('Table_Name')")
for i in a:
print(i)
开源项目https://github.com/WolfgangFahl/DgraphAndWeaviateTest (我是其提交者)中的sqlite3 包装器基于问题 10 添加了一个功能:添加了从 sqlite3 检索架构信息的支持
def getTableList(self):
'''
get the schema information from this database
'''
tableQuery="SELECT name FROM sqlite_master WHERE type='table'"
tableList=self.query(tableQuery)
for table in tableList:
tableName=table['name']
columnQuery="PRAGMA table_info('%s')" % tableName
columns=self.query(columnQuery)
table['columns']=columns
return tableList
这将返回您可以打印的字典列表。
请参阅带有输出的python 单元测试用例:
[{'name': 'Person', 'columns': [{'cid': 0, 'name': 'name', 'type': 'TEXT', 'notnull': 0, 'dflt_value': None, 'pk': 1}, {'cid': 1, 'name': 'born', 'type': 'DATE', 'notnull': 0, 'dflt_value': None, 'pk': 0}, {'cid': 2, 'name': 'numberInLine', 'type': 'INTEGER', 'notnull': 0, 'dflt_value': None, 'pk': 0}, {'cid': 3, 'name': 'wikidataurl', 'type': 'TEXT', 'notnull': 0, 'dflt_value': None, 'pk': 0}, {'cid': 4, 'name': 'age', 'type': 'FLOAT', 'notnull': 0, 'dflt_value': None, 'pk': 0}, {'cid': 5, 'name': 'ofAge', 'type': 'BOOLEAN', 'notnull': 0, 'dflt_value': None, 'pk': 0}, {'cid': 6, 'name': 'lastmodified', 'type': 'TIMESTAMP', 'notnull': 0, 'dflt_value': None, 'pk': 0}]}]
您可以按照您认为适合示例表声明的方式进行漂亮打印:
CREATE TABLE Person(name TEXT PRIMARY KEY,born DATE,numberInLine INTEGER,wikidataurl TEXT,age FLOAT,ofAge BOOLEAN,lastmodified TIMESTAMP)
在这种情况下,它是自动从数据字典列表中派生出来的......
现在还有一些 plantuml 支持来获取可以渲染的 plantuml 源代码,例如
def testEntityInfo(self):
'''
test creating entityInfo from the sample record
'''
listOfRecords=Sample.getRoyals()
entityInfo=EntityInfo(listOfRecords[:3],'Person','name',debug=True)
self.assertEqual("CREATE TABLE Person(name TEXT PRIMARY KEY,born DATE,numberInLine INTEGER,wikidataurl TEXT,age FLOAT,ofAge BOOLEAN,lastmodified TIMESTAMP)",entityInfo.createTableCmd)
self.assertEqual("INSERT INTO Person (name,born,numberInLine,wikidataurl,age,ofAge,lastmodified) values (:name,:born,:numberInLine,:wikidataurl,:age,:ofAge,:lastmodified)",entityInfo.insertCmd)
self.sqlDB=SQLDB(debug=self.debug,errorDebug=True)
entityInfo=self.sqlDB.createTable(listOfRecords[:10],entityInfo.name,entityInfo.primaryKey)
tableList=self.sqlDB.getTableList()
if self.debug:
print (tableList)
self.assertEqual(1,len(tableList))
personTable=tableList[0]
self.assertEqual("Person",personTable['name'])
self.assertEqual(7,len(personTable['columns']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.