无法使用 QSqlTableModel 显示来自远程 QTableView 数据库的表(据我了解,与数据库本身的连接不起作用)。有一个代码不起作用,我无法弄清楚问题是什么......
import sys
from PySide2.QtCore import QSize
from PySide2.QtSql import QSqlDatabase, QSqlTableModel
from PySide2.QtWidgets import QApplication, QMainWindow, QTableView
db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("server167.hosting.reg.ru")
db.setDatabaseName("db")
db.setUserName("<user name>")
db.setPassword("<password>")
db.open()
print(db, type(db))
if db.open():
print("Database Open!")
else:
print("Database NOT Open!")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.table = QTableView()
self.model = QSqlTableModel(db=db)
self.table.setModel(self.model)
self.model.setTable("objects")
self.model.select()
self.setMinimumSize(QSize(1024, 600))
self.setCentralWidget(self.table)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
我检查了100次连接数据,由于填充表的代码是100%执行的,我当然可以把连接器全部拿走,但我真的很想用Qt =)填充数据库表的代码:
import mysql.connector as mysql
mysql_conn = mysql.connect(
host='server167.hosting.reg.ru',
user='u1082920_root',
password='1501kZn1501!',
database = 'u1082920_docs_db'
)
with mysql_conn as connection:
cursor = connection.cursor()
cursor.execute("""DROP TABLE IF EXISTS objects""")
cursor.execute("""CREATE TABLE objects(id INTEGER PRIMARY KEY, data TEXT NOT NULL,
plan TEXT NOT NULL, name_plan TEXT NOT NULL)""")
# # SQL запрос на вставку
query = f"INSERT INTO objects (id, data,plan,name_plan) VALUES ('{1}', '{str(2)}', '{str(3)}', '{str(4)}')"
cursor.execute(query)
query = f"INSERT INTO objects (id, data,plan,name_plan) VALUES ('{2}', '{str(2)}', '{str(3)}', '{str(4)}')"
cursor.execute(query)
connection.commit()
connection.close()