QSql 连接并从数据库读取示例? - 驱动程序未加载
我最近开始发现需要从 __mysql 模块更改为 PyQt 的 QSql,但不知道从哪里开始。我现在想做的就是从数据库中读取并打印结果。这是我得到的最远的结果,但我不断收到从 query.exec_() 函数返回的“驱动程序未加载驱动程序未加载”错误。
请帮忙!
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()
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 returned values
while query.next():
print "query value" , query.value(0).toString()
db.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊啊!!!这种事总是会发生!带着问题坐了一天,最后决定发帖询问,发布问题后大约 30 分钟,你就找到了解决方案!
对于那些感兴趣的人,我遇到了与这个人相同的问题。
基本上你必须在执行 sql 代码之前创建一个 QApplication 实例...即
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