import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtSql import *
db = QSqlDatabase.addDatabase ("QSQLITE")
# db.setDatabaseName (":memory:")
db.setDatabaseName ("test.sqlite")
db.open ()
query = db.exec_ ("CREATE TABLE IF NOT EXISTS colors (name TEXT,"
"red INTEGER, green INTEGER, blue INTEGER)")
db.exec_ ("INSERT INTO colors (name, red, green, blue) VALUES (\"blue\", 0, 0, 255)")
db.close ()
#!/usr/bin/env python
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtSql import *
# --------------------------------------------------------------------------
class DatabaseInfo (object) :
def __init__ (self) :
self.item_list = [ ]
class TableInfo (object) :
def __init__ (self) :
self.item_name = ""
self.item_list = [ ]
class ColumnInfo (object) :
def __init__ (self) :
self.item_name = ""
# --------------------------------------------------------------------------
class DbView (QWidget):
def __init__ (self, parent = None) :
super (DbView, self).__init__ (parent)
layout = QVBoxLayout ()
self.setLayout (layout)
table = QTableView ()
layout.addWidget (table)
db = QSqlDatabase.addDatabase ("QSQLITE")
# db.setDatabaseName (":memory:")
db.setDatabaseName ("test.sqlite")
db.open ()
query = db.exec_ ("CREATE TABLE IF NOT EXISTS colors (name TEXT, red INTEGER, green INTEGER, blue INTEGER)")
db.exec_ ("INSERT INTO colors (name, red, green, blue) VALUES (\"blue\", 0, 0, 255)")
insert = QSqlQuery (db)
insert.prepare ("INSERT INTO colors (name, red, green, blue) VALUES (:name, :red, :green, :blue)")
insert.bindValue (":name", "green")
insert.bindValue (":red", QVariant (0))
insert.bindValue (":green", QVariant (255))
insert.bindValue (":blue", QVariant (0))
insert.exec_ ()
model = QSqlTableModel (self, db)
model.setTable ("colors")
model.select ()
table.setModel (model)
database_info = DatabaseInfo ()
database_info.item_name = db.databaseName()
database_info.item_expand = True
table_list = db.tables()
for table_name in table_list :
query = db.exec_ ("SELECT * FROM " + table_name)
table_info = TableInfo ()
table_info.item_name = table_name
table_info.item_expand = True
database_info.item_list.append (table_info)
rec = query.record ()
for k in range (rec.count ()) :
txt = rec.fieldName (k)
column_info = ColumnInfo ()
column_info.item_name = txt;
table_info.item_list.append (column_info)
if __name__ == "__main__" :
app = QApplication (sys.argv)
win = DbView ()
win.show ()
app.exec_ ()