我要将PyQt5连接到MySQL。不幸的是我收到错误'Driver not loaded'。 Python说驱动程序在里面:
from PyQt5.QtSql import QSqlDatabase
print(list(map(str, QSqlDatabase.drivers())))
答案:['QSQLITE','QMYSQL','QMYSQL3','QODBC','QODBC3','QPSQL','QPSQL7'] 我使用Windows 7并安装了Qt Designer
这是我的代码:
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys
app = QApplication(sys.argv)
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');
谁有经验。非常感谢你
答案 0 :(得分:4)
问题出在应用程序启动过程中。如果是PyQt,则需要启动GUI应用程序,然后才能实际使用其下的类。要记住的另一件事,总是尝试查看实际错误。在您的情况下,您正在强制使用lastError()
方法并在此之前遗漏了一些有价值的观点。您仅在观看Driver not loaded
错误。但是在该终端之前还显示了QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins
这个错误,清楚地表明了找不到驱动程序的真正原因。
要创建QCoreApplication,您需要在代码中添加它-
if __name__ == '__main__':
app = QApplication(sys.argv)
因此您的代码可以是-
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()
由于没有配置MySql,因此我已经使用SQlite数据库完成了一个示例。演示-
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()
答案 1 :(得分:3)
我正在像这样将PyQt5连接到MySQL:
from PyQt5 import QtCore, QtGui, QtWidgets
#from PyQt5.QtSql import QSqlDatabase, QSqlQuery
import MySQLdb as mysql # pip install mysqlclient
def convert(in_data):
def cvt(data):
try:
return ast.literal_eval(data)
except Exception:
return str(data)
return tuple(map(cvt, in_data))
class Ui_MainWindow(object):
def loadconection(self):
# HostName UserName Password DatabaseName
db = mysql.connect(host="localhost",user="user", passwd="password",db="testdb")
with db:
cur = db.cursor()
# table vvvvvvvvv
rows = cur.execute("""select * from pyqt5data""")
data = cur.fetchall()
for row in data:
self.add_table(convert(row))
cur.close()
def add_table(self, columns):
rowPosition = self.tableWidget.rowCount()
self.tableWidget.insertRow(rowPosition)
for i, column in enumerate(columns):
self.tableWidget.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(str(column)))
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 520)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(35, 21, 731, 401))
self.tableWidget.setColumnCount(5)
self.tableWidget.setHorizontalHeaderLabels(['Id', 'Name', 'Email', 'Phone', 'Note'])
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setAlternatingRowColors(True)
self.tableWidget.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
self.btn_abrirbd2 = QtWidgets.QPushButton(self.centralwidget)
self.btn_abrirbd2.setGeometry(QtCore.QRect(340, 460, 75, 23))
self.btn_abrirbd2.setObjectName("btn_abrirbd2")
self.btn_abrirbd2.clicked.connect(self.loadconection)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_abrirbd2.setText(_translate("MainWindow", "SELECT mysql"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
答案 2 :(得分:0)
从提升权限的命令提示符运行:
o要么:pip install --only-binary:all:mysqlclient
o或:首先安装构建工具https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017,然后运行:pip install mysqlclient)(此选项要求您下载4gb +文件)
完成后,您可以像这样进行连接:
from PyQt5 import QtSql
import mysql.connector
class DbConnection(object):
def connect(self):
try:
self.__db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
self.__db.setHostName("localhost")
self.__db.setDatabaseName("yourDB")
self.__db.setUserName("root")
self.__db.setPassword("yourPassword")
self.__ok = self.__db.open()
except:
print(self.__db.lastError().text())
return self.__ok
def closeConnection(self):
try:
self.__db.close()
except:
pass
if __name__ == "__main__":
from PyQt5 import QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
conn = DbConnection()
print("Connected: " + str(conn.connect()))
conn.closeConnection()
sys.exit(app.exec_())
答案 3 :(得分:0)
我通过安装PyQt5的12.0版本而不是14版解决了此问题。 如果将libmysql.dll的副本放在项目文件夹中,也可能会有帮助