Issue
I am trying to get data from My maria DB using PyQt6. its not working
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self._table_view = QTableView(self)
self.setCentralWidget(self._table_view)
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setHostName("127.0.0.1")
self.db.setDatabaseName("secqtydb")
self.db.setUserName("root")
self.db.setPassword("1234")
print("db is - ", self.db.open())
self.db.open()
self.qry = "SELECT * FROM files"
self.query = QSqlQuery()
print("query2 is-- ", self.query.prepare(self.qry))
self.query.prepare(self.qry)
self.query.exec()
for row_number, row_data in enumerate(self.query.result()):
for column_number, data in enumerate(row_data):
self.tableWidget.setItem(row_number, column_number, self._table_view(data))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())
self.bd.open() i get true but self.query.prepare(self.qry) i get False please help someone
where is no tutorial for PyQt6 i tried to look on the web but i found Tutorials only for PyQt5
Solution
I see that you're trying to connect to a MariaDB database using PyQt6.
Few issues in your code that need to be addressed:
- You're using the SQLite driver
("QSQLITE")
for yourQSqlDatabase
, but you should be using the MariaDB driver("QMYSQL")
. Ref -https://doc.qt.io/qt-6/sql-driver.html
Note : QMYSQL
driver will not be available mostly. you have to manually download the dlls and try it
- You should create a
QSqlTableModel
orQSqlQueryModel
to work with your database data and populate theQTableView
.
'''
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView
from PyQt6.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self._table_view = QTableView(self)
self.setCentralWidget(self._table_view)
self.db = QSqlDatabase.addDatabase("QMYSQL")
self.db.setHostName("127.0.0.1")
self.db.setDatabaseName("secqtydb")
self.db.setUserName("root")
self.db.setPassword("1234")
if self.db.open():
print("Connected to the database")
self.model = QSqlTableModel(self)
self.model.setTable("files") # Set the table name
if self.model.select():
self._table_view.setModel(self.model)
else:
print("Failed to select data from the table")
else:
print("Failed to connect to the database")
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())
Hope this helps
Answered By - Prudhviraj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.