Qt代码实现数据库登录功能
时间: 2023-09-17 10:09:50 浏览: 45
以下是一个使用 Qt 实现数据库登录功能的示例代码:
```cpp
#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
// 数据库登录窗口类
class LoginDialog : public QDialog
{
Q_OBJECT
public:
LoginDialog(QWidget *parent = nullptr) : QDialog(parent)
{
// 初始化界面
setupUi(this);
// 设置数据库类型
dbTypeComboBox->addItems(QSqlDatabase::drivers());
// 设置默认数据库信息
dbTypeComboBox->setCurrentText("QMYSQL");
hostLineEdit->setText("localhost");
portSpinBox->setValue(3306);
usernameLineEdit->setText("root");
passwordLineEdit->setEchoMode(QLineEdit::Password);
}
private slots:
// 处理登录按钮点击事件
void on_loginButton_clicked()
{
// 获取数据库信息
QString dbType = dbTypeComboBox->currentText();
QString host = hostLineEdit->text();
int port = portSpinBox->value();
QString username = usernameLineEdit->text();
QString password = passwordLineEdit->text();
// 打开数据库连接
QSqlDatabase db = QSqlDatabase::addDatabase(dbType);
db.setHostName(host);
db.setPort(port);
db.setUserName(username);
db.setPassword(password);
if (!db.open()) {
qWarning() << "Failed to open database:" << db.lastError().text();
return;
}
// 测试数据库连接
QSqlQuery query(db);
if (!query.exec("SELECT VERSION()")) {
qWarning() << "Failed to execute query:" << query.lastError().text();
db.close();
return;
}
if (query.next()) {
QString version = query.value(0).toString();
qDebug() << "Database version:" << version;
}
// 关闭数据库连接
db.close();
// 关闭登录窗口
accept();
}
private:
// 界面控件
Ui::LoginDialog *ui;
};
// 应用程序主函数
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 显示登录窗口
LoginDialog loginDialog;
if (loginDialog.exec() != QDialog::Accepted) {
return 0;
}
// 显示主窗口
QMainWindow mainWindow;
mainWindow.show();
return app.exec();
}
```
在这个示例中,我们创建了一个 `LoginDialog` 类,该类继承自 `QDialog`,用于显示数据库登录界面。在 `LoginDialog` 类中,我们使用 Qt 提供的 `QSqlDatabase` 和 `QSqlQuery` 类来连接数据库和执行 SQL 查询。当用户点击登录按钮时,我们将获取用户输入的数据库信息,并使用 `QSqlDatabase` 连接到数据库。如果连接成功,我们将使用 `QSqlQuery` 执行一个简单的 SQL 查询以测试数据库连接。最后,我们将关闭数据库连接,并关闭登录窗口。
在应用程序的主函数中,我们首先显示登录窗口,并等待用户登录。如果用户成功登录,我们将显示主窗口。