您的位置:首页 > 编程语言 > Qt开发

Qt13 Creating connection open and close function with sqlite database

2016-03-30 07:14 549 查看
1.  drag a label widget on employeeinfo window, name as label_sec_status

2. modify login.h

#ifndef LOGIN_H
#define LOGIN_H

#include <QMainWindow>
#include <QtSql>
#include <QDebug>
#include <QFileInfo>

#include "employeeinfo.h"

namespace Ui {
class login;
}

class login : public QMainWindow
{
Q_OBJECT

public:
static void connClose()
{
connected = false;
mydb.close();
mydb = QSqlDatabase();
mydb.removeDatabase(QSqlDatabase::defaultConnection);
}
static bool connOpen()
{
if( !connected )
{
mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("D:/work_files/sqlite-tools-win32-x86-3120000/company.db");

if(!mydb.open())
{
qDebug() << "Failed to open the database";
connected = false;
}
else
{
qDebug() << "Connected...";
connected = true;
}
}
return connected;
}

public:
explicit login(QWidget *parent = 0);
~login();

private slots:
void on_pushButton_clicked();

private:
Ui::login *ui;
static QSqlDatabase mydb;
static bool connected;
};

#endif // LOGIN_H


3.modify login.cpp

#include "login.h"
#include "ui_login.h"

QSqlDatabase login::mydb;
bool login::connected = false;

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

QPixmap pix("G:/TestQT/Sqlite_DB/icon/panda.png");
ui->label_pic->setPixmap(pix);

if(!connOpen())
{
ui->label->setText("Failed to open the database") ;

}
else
{
ui->label->setText("Connected...") ;

}

}

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

void login::on_pushButton_clicked()
{
QString username, password;
username = ui->lineEdit_Username->text();
password = ui->lineEdit_Password->text();

if(!connOpen())
{
ui->label->setText("Failed to open the database");
return ;
}

QSqlQuery qry;

QString stmt = "select * from employeeinfo where username='"+ username +"' and password='"+ password +"'";
qry.prepare(stmt);
if( qry.exec())
{
int count = 0;
while(qry.next())
count++;
if( count == 1 )
{
ui->label->setText("username and password is correct");
connClose();
this->hide();
EmployeeInfo employeeinfo;
employeeinfo.setModal(true);
employeeinfo.exec();

}
else if( count > 1 )
ui->label->setText("Duplicate username and password");
if( count < 1 )
ui->label->setText("username and password is not correct");
}
else
{
qDebug() << qry.lastError();
}
}


4. modify employeeinfo.cpp
#include "employeeinfo.h"
#include "ui_employeeinfo.h"
#include "login.h"
EmployeeInfo::EmployeeInfo(QWidget *parent) :
QDialog(parent),
ui(new Ui::EmployeeInfo)
{
ui->setupUi(this);
if(!login::connOpen())
{
ui->label_sec_status->setText("Failed to open the database") ;

}
else
{
ui->label_sec_status->setText("Connected...") ;

}
}

EmployeeInfo::~EmployeeInfo()
{
delete ui;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: