在这个常见的例子中:
from PyQt4 import QtCore, QtGui, QtSql
import psycopg2 as psycopg
import sys
#try:
conn = psycopg.connect("dbname='metalarc1' user='postgres' host='192.168.1.136'
password='admin' port='5433'");
#except:
# print "I am unable to connect to the database"
def initializeModel(model):
# cur.execute("""select * from employee""")
# rows = cur.fetchall()
model.setTable("employee")
model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
model.setRelation(2, QtSql.QSqlRelation('city', 'id', 'name'))
model.setRelation(3, QtSql.QSqlRelation('country', 'id', 'name'))
model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
model.setHeaderData(1, QtCore.Qt.Horizontal, "Name")
model.setHeaderData(2, QtCore.Qt.Horizontal, "City")
model.setHeaderData(3, QtCore.Qt.Horizontal, "Country")
model.select()
def createView(title, model):
view = QtGui.QTableView()
view.setModel(model)
view.setItemDelegate(QtSql.QSqlRelationalDelegate(view))
view.setWindowTitle(title)
return view
def createRelationalTables():
query = QtSql.QSqlQuery()
cur.execute("""create table employee(id int primary key not null, name
varchar(20), city int, country int)""")
cur.execute("""insert into employee values(1, 'Espen', 5000, 47)""")
cur.execute("""insert into employee values(2, 'Harald', 80000, 49)""")
cur.execute("""insert into employee values(3, 'Sam', 100, 41)""")
cur.execute("""create table city(id int primary key not null, name varchar(20))""")
cur.execute("""insert into city values(100, 'San Jose')""")
cur.execute("""insert into city values(5000, 'Oslo')""")
cur.execute("""insert into city values(80000, 'Munich')""")
cur.execute("""create table country(id int primary key not null, name varchar(20))""")
cur.execute("""insert into country values(41, 'USA')""")
cur.execute("""insert into country values(47, 'Norway')""")
cur.execute("""insert into country values(49, 'Germany')""")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
createRelationalTables()
model = QtSql.QSqlRelationalTableModel()
initializeModel(model)
view = createView("Relational Table Model", model)
view.show()
sys.exit(app.exec_())
表格创建得很好并且已填充。但是model.select()返回False,视图弹出空白(没有列标题或数据) 当我使用QSQLITE数据库运行相同的代码时,它工作正常。我觉得它必须非常简单,因为如果我:
,数据就在那里cur.execute("""select * from employee""")
rows = cur.fetchall()
rows[0]
(1, 'Espen', 5000, 47)
我可以肯定会使用一些帮助 - 在这2天内一直在努力。感谢
答案 0 :(得分:0)
您需要使用QSqlDatabase
连接到PostgreSQL数据库,而不是导入psycopg2。
连接from the docs的一个(pythonised)示例:
db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName("acidalia")
db.setDatabaseName("customdb")
db.setUserName("mojito")
db.setPassword("J0a1m8")
ok = db.open()
当您使用QSqlQuery
和QSqlRelationalTableModel.setTable()
时,他们会使用默认的QSqlDatabase
连接,除非您在创建连接时指定连接名称。在上面的示例中,您没有 - 我猜你何时使用'QSQLITE'数据库它是QSqlDatabase
?