[英]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.