开发者

QSql connect and read from Database example? - Driver not loaded

开发者 https://www.devze.com 2023-04-04 18:20 出处:网络
I\'ve recently started found the need to change from the __mysql module to PyQt\'s QSql but have nooo idea whatsoever where to start. All I want to do (for now) is read from a database and print the r

I've recently started found the need to change from the __mysql module to PyQt's QSql but have nooo idea whatsoever where to start. All I want to do (for now) is read from a database and print the results. This is the furthest I've gotten but I keep getting a "Driver not loaded Driver not loaded" error returned from the query.exec_() function.

Please help!

db = QSqlDatabase.addDatabase("QMYSQL")

db.setHostName ( db_host )
db.setUserName ( db_user )
db.setPassword ( db_passwd )
db.setDatabaseName ( db_db )
db.setPort ( db_port )

db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1")
db.open()

defaultDB = QSqlDatabase.database()
query = QSqlQuery("SELECT * FROM Users")

qe = query.exec_()
print "query exec" , query.exec_()
if not qe:              # if error
    print QSqlQuery.lastError( query ).text()
else:                   # else display 开发者_StackOverflow社区returned values
    while query.next():
        print "query value" , query.value(0).toString()


db.close()


AAAAHH!!!This always happens! Sit with a problem for a day, finally decide to post and ask about it and about 30 mins after you post your problem, you find a solution!

For those interested, I had the same problem as this guy.

Basically you HAVE to create a QApplication instance BEFORE your sql code gets executed... i.e

# this little monkey has to be here
app = QApplication(sys.argv)


# rest of the code
db = QSqlDatabase.addDatabase("QMYSQL")

db.setHostName ( db_host )
db.setUserName ( db_user )
db.setPassword ( db_passwd )
db.setDatabaseName ( db_db )
db.setPort ( db_port )

db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1")
db.open()

defaultDB = QSqlDatabase.database()
query = QSqlQuery("SELECT * FROM Users")

qe = query.exec_()
print "query exec" , query.exec_()
if not qe:              # if error
    print QSqlQuery.lastError( query ).text()
else:                   # else display returned values
    while query.next():
        print "query value" , query.value(0).toString()


db.close()
0

精彩评论

暂无评论...
验证码 换一张
取 消