Sourabh Sourabh - 7 months ago 89
SQL Question

Not able to connect to mysql server from PyQt5

I am trying to connect to MySQL data base through

QtSql.QSqlDatabase
class in PyQt5.
Here is my code:

from PyQt5 import QtWidgets
from PyQt5 import QtSql
import sys

app = QtWidgets.QApplication(sys.argv)
db = QtSql.QSqlDatabase()
db.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setUserName("root")
db.setPassword("*****") #correct password here
db.setDatabaseName("root")
print(db.open())
print(db.lastError().text())
print(db.drivers())


I always get error as
Driver not loaded
. Here is the o/p from my code:

False
Driver not loaded Driver not loaded
['QSQLITE', 'QMYSQL', 'QMYSQL3', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']


PyQt5 is 64bit version built with python3.
Mysql server is running.
There contents of C:\Python35\Lib\site-packages\PyQt5\plugins\sqldrivers is:

list of sql drivers

Can anyone help here?

Answer

Error was here

db = QtSql.QSqlDatabase()
db.addDatabase('QMYSQL')

as addDatabase is a static function. Correct code is this

db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
Comments