Qt5数据库PostgreSQL应用3

用PostgreSQL来做一个Qt登陆界面的数据库。

首先,用pgAdmin创建要用到的数据库。

新建一个数据表

设定键

添加数据

得到数据表

新建一个UI

添加代码

LoginDialog.h

#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H

#include <QDialog>

#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>

namespace Ui {
class LoginDialog;
}

class LoginDialog : public QDialog
{
    Q_OBJECT

public:
    explicit LoginDialog(QWidget *parent = nullptr);
    ~LoginDialog();

private:
    Ui::LoginDialog *ui;

    QSqlDatabase db;
private slots:
    void on_pushButton_clicked();
};

#endif // LOGINDIALOG_H

LoginDialog.cpp

#include "logindialog.h"
#include "ui_logindialog.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName("127.0.0.1");
    db.setUserName("postgres");
    db.setPassword("postgres");
    db.setDatabaseName("postgres");
    if(!db.open())
    {
        qDebug() << "Failed to connect to databae.";
    }
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::on_pushButton_clicked()
{
    qDebug() << "try login";
    QString username = ui->lineEdit->text();
    QString password = ui->lineEdit_2->text();
    QSqlQuery query;
    if(query.exec("SELECT employeeid from user WHERE username = '" + username + "' AND password = '" + password + "'"))
    {
        if(query.size() > 0)
        {
            qDebug() << "login success";
//            while(query.next())
//            {
//                QString empolyeeID = query.value(0).toString();
//                QSqlQuery query2;
//                if(query2.exec("SELECT name, age, gender, married FROM employee WHERE id = " + empolyeeID))
//                {
//                    while(query2.next())
//                    {
//                        QString name = query2.value(0).toString();
//                        QString age = query2.value(1).toString();
//                        int gender = query2.value(2).toInt();
//                        bool married = query2.value(3).toBool();
//                        ui->name
//                    }
//                }
//            }
        }
    }
}

运行代码,得到

多谢,亲爱的美美。

猜你喜欢

转载自blog.csdn.net/islinyoubiao/article/details/113784600