The problem was in the application start process. In case of PyQt, you need to start a GUI application before you can actually use the classes under it. Another thing to remember, always try to see the actual error. In your case, you are forcing a lastError() method and missing some valuable points before that. You are only watching the Driver not loaded error. But before that terminal also showed QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins this error, which clearly shows the actual reason of why the driver is not found.
To make a QCoreApplication, you need to add this in your code -
if __name__ == '__main__':
app = QApplication(sys.argv)
So your code can be -
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys
def dbcon():
db = QSqlDatabase.addDatabase('QMYSQL')
db.setHostName('****')
db.setDatabaseName('****')
db.setUserName('****')
db.setPassword('****')
ok = db.open()
if not ok: print(db.lastError().text())
# else: print("connected")
query = QSqlQuery(db)
query.exec_('SELECT * FROM tbl_Customers')
if __name__ == '__main__':
app = QApplication(sys.argv)
dbcon()
I have done a sample with SQlite database, as I have no MySql configured. The demo -
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication, QMessageBox
def createDB():
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sports.db')
if not db.open():
QMessageBox.critical(None, ("Cannot open database"),
("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n"
"Click Cancel to exit."),
QMessageBox.Cancel)
return False
query = QtSql.QSqlQuery()
query.exec_("create table sportsmen(id int primary key, "
"firstname varchar(20), lastname varchar(20))")
query.exec_("insert into sportsmen values(101, 'Roger', 'Federer')")
query.exec_("insert into sportsmen values(102, 'Christiano', 'Ronaldo')")
query.exec_("insert into sportsmen values(103, 'Ussain', 'Bolt')")
query.exec_("insert into sportsmen values(104, 'Sachin', 'Tendulkar')")
query.exec_("insert into sportsmen values(105, 'Saina', 'Nehwal')")
return True
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
createDB()