Qt interface program data model is saved using MySQL database

example

basic framework

Design a data class object used to store the LAB color space.
h file:

#ifndef COLORSPACE_H
#define COLORSPACE_H

#include <QString>
#include <QUuid>

class ColorSpace
{
private:
    QUuid mId;
    QString mColorName;
    QString mL;
    QString mA;
    QString mB;

public:
    ColorSpace();
    ColorSpace(QUuid uuid);

    QUuid getId(){ return mId;}
    QString getColorName(){return mColorName;}
    QString getL(){return mL;}
    QString getA(){return mA;}
    QString getB(){return mB;}

    void setColorName(QString colorname){mColorName = colorname;}
    void setL(QString l) {mL = l;}
    void setA(QString a) {mA = a;}
    void setB(QString b) {mB = b;}

    void setLABint(int l, int a, int b)
    {
        setL(QString::number(l));
        setA(QString::number(a));
        setB(QString::number(b));
    }
};

#endif // COLORSPACE_H

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

cpp file:

#include "colorspace.h"

ColorSpace::ColorSpace()
{
    mId = QUuid::createUuid().toString();
    mColorName = "A";
    mL = "0";
    mA = "127";
    mB = "127";
}

ColorSpace::ColorSpace(QUuid uuid)
{
    mId = uuid.toString();
    mColorName = "A";
    mL = "0";
    mA = "127";
    mB = "127";
}

This data model is used to store a color and its corresponding L, A, and B channel values ​​of the LAB color space, and UUID is a data used when saving the database.

Multiple colors are used in an application, so a ColorSpaceLab class needs to be designed to manage them.

h file:

#ifndef COLORSPACELAB_H
#define COLORSPACELAB_H
#include <QList>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "colorspace.h"
#include "basehelper.h"

class ColorSpaceLab
{
public:
    ColorSpaceLab();
    static ColorSpaceLab* get();
    BaseHelper* mbh;

private:
    static ColorSpaceLab* pColorSpaceLab;

public:
    void addColorSpace(ColorSpace c);
    void deleteColorSpaceByUuid(ColorSpace c);
    void deleteAllColorSpace();
    QList<ColorSpace> getColorSpaces();
    ColorSpace getColorSpaceByUuid(QUuid id);
    ColorSpace getColorSpaceByColorName(QString color);
    void updateColorSpacebyUuid(ColorSpace colorSpace);
    void updateColorSpacebyName(ColorSpace colorSpace);
    static QString AnalyzeColor(int l, int a, int b);
};

#endif // COLORSPACELAB_H

cpp file:

#include "colorspacelab.h"

ColorSpaceLab* ColorSpaceLab::pColorSpaceLab = nullptr;

ColorSpaceLab::ColorSpaceLab()
{
    mbh = BaseHelper::get();
}

ColorSpaceLab* ColorSpaceLab::get()
{
    if (pColorSpaceLab == nullptr) {
        pColorSpaceLab = new ColorSpaceLab();
    }
    return pColorSpaceLab;
}

void ColorSpaceLab::addColorSpace(ColorSpace c)      //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("INSERT INTO COLORSPACE VALUES(:_id,:uuid,:color_name,:l,:a,:b)");
    query.bindValue(":uuid",c.getId().toString());
    query.bindValue(":color_name",c.getColorName());
    query.bindValue(":l",c.getL());
    query.bindValue(":a",c.getA());
    query.bindValue(":b",c.getB());
    bool success = query.exec();
    if(!success)
    {
        QSqlError lastError = query.lastError();
        QMessageBox msgBox;
        msgBox.setText("database insert failed:" + lastError.driverText() + lastError.databaseText());
        msgBox.exec();
        return;
    }
}

void ColorSpaceLab::deleteColorSpaceByUuid(ColorSpace c)   //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("DELETE FROM COLORSPACE WHERE uuid = ?");
    query.bindValue(0,c.getId().toString());
    bool success = query.exec();
    if(!success)
    {
        QSqlError lastError = query.lastError();
        QMessageBox msgBox;
        msgBox.setText("database delete failed:" + lastError.driverText() + lastError.databaseText());
        msgBox.exec();
    }
}

void ColorSpaceLab::deleteAllColorSpace()             //测试通过
{
    //先查出所有的记录,再根据uuid删除
    QList<ColorSpace> listcs;
    listcs = getColorSpaces();
    for(int i = 0;i<listcs.size();i++)
        deleteColorSpaceByUuid(listcs.at(i));
}

QList<ColorSpace> ColorSpaceLab::getColorSpaces()           //测试通过
{
    QList<ColorSpace> listcs;
    QSqlQuery query(mbh->db);
    query.exec("SELECT * FROM COLORSPACE");

    while(query.next())
    {
        QUuid uuid(query.value(1).toString());
        ColorSpace cs(uuid);
        cs.setColorName(query.value(2).toString());
        cs.setL(query.value(3).toString());
        cs.setA(query.value(4).toString());
        cs.setB(query.value(5).toString());
        listcs.append(cs);
    }
    return listcs;
}

ColorSpace ColorSpaceLab::getColorSpaceByUuid(QUuid id)       //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("SELECT * FROM COLORSPACE WHERE uuid = ?");
    query.bindValue(0,id.toString());
    query.exec();

    if(query.next())
    {
        QUuid uuid(query.value(1).toString());
        ColorSpace cs(uuid);
        cs.setColorName(query.value(2).toString());
        cs.setL(query.value(3).toString());
        cs.setA(query.value(4).toString());
        cs.setB(query.value(5).toString());
        return cs;
    }
    else
        return NULL;
}

ColorSpace ColorSpaceLab::getColorSpaceByColorName(QString color)      //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("SELECT * FROM COLORSPACE WHERE color_name = ?");
    query.bindValue(0,color);
    bool success = query.exec();
    if(!success)
    {
        QSqlError lastError = query.lastError();
        QMessageBox msgBox;
        msgBox.setText("database query failed:" + lastError.driverText() + lastError.databaseText());
        msgBox.exec();
    }
    if(query.next())
    {
        QUuid uuid(query.value(1).toString());
        ColorSpace cs(uuid);
        cs.setColorName(query.value(2).toString());
        cs.setL(query.value(3).toString());
        cs.setA(query.value(4).toString());
        cs.setB(query.value(5).toString());
        return cs;
    }
    else
    {
        ColorSpace cs(QUuid::createUuid());
        cs.setA("0");
        return cs;
    }
}

void ColorSpaceLab::updateColorSpacebyUuid(ColorSpace colorSpace)    //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("UPDATE COLORSPACE SET color_name = ?,l = ?, a = ?, b = ?  WHERE uudi = ?");
    query.bindValue(0,colorSpace.getColorName());
    query.bindValue(1,colorSpace.getL());
    query.bindValue(2,colorSpace.getA());
    query.bindValue(3,colorSpace.getB());
    query.bindValue(4,colorSpace.getId().toString());
    bool success = query.exec();
    if(!success)
    {
        QSqlError lastError = query.lastError();
        QMessageBox msgBox;
        msgBox.setText("database update failed:" + lastError.driverText() + lastError.databaseText());
        msgBox.exec();
    }
}

void ColorSpaceLab::updateColorSpacebyName(ColorSpace colorSpace)   //测试通过
{
    QSqlQuery query(mbh->db);
    query.prepare("UPDATE COLORSPACE SET l = ?, a = ?, b = ?  WHERE color_name = ?");
    query.bindValue(0,colorSpace.getL());
    query.bindValue(1,colorSpace.getA());
    query.bindValue(2,colorSpace.getB());
    query.bindValue(3,colorSpace.getColorName());
    bool success = query.exec();
    if(!success)
    {
        QSqlError lastError = query.lastError();
        QMessageBox msgBox;
        msgBox.setText("database update failed:" + lastError.driverText() + lastError.databaseText());
        msgBox.exec();
    }
}

The static pointer variable pColorSpaceLab in the class points to itself, indicating that this class is only instantiated once when used, because an application only needs one color management class.

It should be noted that the message box popped up by QMessageBox can only be implemented in the interface thread. If the main function of QT operates on the lab class, the message can pop up normally. If it is used in other places, you need to change the message box to qDebug.

BaseHelper is also a class that implements functions such as database connection and table creation.

The functions implemented in the color management class ColorSpaceLab include query, add, delete, update by UUID and color name.

The underlying class definitions used

This class uses some lower-level operations BaseHelper.

h file:

#ifndef BASEHELPER_H
#define BASEHELPER_H

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QVariant>
#include <QString>

class BaseHelper
{
public:
    BaseHelper();
    static BaseHelper* get();
    QSqlDatabase db;
private:
    static BaseHelper* pBaseHelper;


};

#endif // BASEHELPER_H

cpp file:

#include "basehelper.h"

BaseHelper* BaseHelper::pBaseHelper = nullptr;

BaseHelper* BaseHelper::get()
{
    if (pBaseHelper == nullptr) {
        pBaseHelper = new BaseHelper();
    }
    return pBaseHelper;
}

BaseHelper::BaseHelper()
{
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("csd");       //这里输入你的数据库名
    db.setUserName("root");
    db.setPassword("123456");   //这里输入你的密码
    if (!db.open())
    {
        QMessageBox::critical(0, QObject::tr("can't open database"),
        "can't connect to database! ", QMessageBox::Cancel);
    }

    //查看表是否存在
    QSqlQuery query(db);
    query.exec("SELECT table_name FROM information_schema.TABLES WHERE table_name ='colorspace'");
    if(query.next())
    {
       QVariant var = query.value(0);
       QString str = var.toString();
    }
    else
    {
        bool success = query.exec("CREATE TABLE COLORSPACE (_id int primary key AUTO_INCREMENT, uuid  varchar(50), color_name  varchar(20), l  varchar(10), a  varchar(10), b  varchar(10))");
        QMessageBox msgBox;
        if(success)
            msgBox.setText("The data table was created successfully.");
        else
            msgBox.setText("Cannot create data table");
        msgBox.exec();
    }

    query.exec("SELECT table_name FROM information_schema.TABLES WHERE table_name ='template'");
    if(query.next())
    {
       QVariant var = query.value(0);
       QString str = var.toString();
    }
    else
    {
        bool success = query.exec("CREATE TABLE TEMPLATE (_id int primary key AUTO_INCREMENT, uuid  varchar(50), title  varchar(20), colors  varchar(300))");
        QMessageBox msgBox;
        if(success)
            msgBox.setText("The data table was created successfully.");
        else
            msgBox.setText("Cannot create data table");
        msgBox.exec();
    }
}

BaseHelper connects to the database and creates the table (if it does not exist) when it is instantiated.

Use of data models

ColorSpace* cs = new ColorSpace();
ColorSpaceLab* pcsl = ColorSpaceLab::get();
QList<ColorSpace> listcs = pcsl->getColorSpaces();
pcsl->deleteColorSpaceByUuid(listcs.at(0));
pcsl->addColorSpace(*cs);
ColorSpace cs1 =  listcs.at(0);
ColorSpace cs2 =  listcs.at(1);
cs1.setA("1");
cs1.setB("1");
cs2.setA("200");
cs2.setB("201");

ColorSpace cs1reture = pcsl->getColorSpaceByColorName(cs1.getColorName());
pcsl->updateColorSpacebyName(cs2);

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/130935459
Recommended