如何使用PyQt和QtSql登录数据库

时间:2018-03-18 06:00:40

标签: python pyqt4 qtsql

我有一个提供注册和登录的PyQt4应用程序。注册效果很好,即凭据按预期存储在数据库中。问题在于登录,它接受任何凭证,包括数据库中不存在的凭证。下面是使用的代码。

self.database1 = QtSql.QSqlDatabase().addDatabase('QMYSQL')
self.database1.setHostName('localhost')
self.database1.setDatabaseName('database')
self.database1.setUserName('root')
self.database1.setPassword('')
if self.database1.open():
    print('Successful')
else:
    print(self.database1.lastError().text())

username = self.userName1.text()
password = self.passwordSlot.text()
query = QtSql.QSqlQuery(self.database1)
credentials = query.prepare("SELECT * FROM credentials WHERE username = ? and password = ?")
if credentials:
    query.addBindValue(username)
    query.addBindValue(password)
    query.exec_()
    self.database1.close()
    print('Successfully logged in')
else:
    print('Failed')

1 个答案:

答案 0 :(得分:1)

prepare()返回一个布尔值,指示语句是否正确,因此无法指示凭据是否匹配,因为正确的语句将始终为true,如果信息在数据库是订单返回至少一个元素,我们可以使用first()

self.database1 = QtSql.QSqlDatabase().addDatabase('QMYSQL')
self.database1.setHostName('localhost')
self.database1.setDatabaseName('database')
self.database1.setUserName('root')
self.database1.setPassword('')
if self.database1.open():
    print('Successful')
else:
    print(self.database1.lastError().text())

username = self.userName1.text()
password = self.passwordSlot.text()
query = QtSql.QSqlQuery(self.database1)
is_valid_query = query.prepare("SELECT * FROM credentials WHERE username = ? and password = ?")
if is_valid_query:
    query.addBindValue(username)
    query.addBindValue(password)
    if query.exec_():
        if query.first():
            print('Successfully logged in')
        else:
            print('Failed')
    else:
        print(query.lastError().text())
self.database1.close()