QT's mysql (database) best practices and FAQs

When it comes to the database, first of all, Amway has a software Navicat Premium, which is very convenient to query the database 

The QMysql driver is a plugin used by the Qt SQL module to communicate with the MySQL database. To compile the QMysql driver, you need to meet the following conditions:

  • You need to install the MySQL client library and development header files, which are usually provided with the MySQL installation program, or can be downloaded from the MySQL official website . Note that you need to choose the correct database library file according to your Qt architecture (32 or 64 bit).
  • You need to obtain the Qt source code, which can be downloaded from the Qt official website . You can choose the source code that matches your Qt version, or you can choose the latest source code.
  • You need to use qmake and make tools to compile the QMysql driver. These tools are usually provided with the Qt installation program, or can be downloaded from the Qt official website . Note that you need to choose the correct tool for your operating system and compiler.

Since the current version of QT's Qmysql is not installed during installation, you need to compile this dll file by yourself.

The steps to compile the relevant dll files of QMysql are as follows:

  • Open the Qt command prompt and enter the qt/src/plugins/sqldrivers/mysql folder in the Qt source code directory, for example:
F:\QT\5.12.9\Src\qtbase\src\plugins\sqldrivers\mysql

Then comment out the following line of code: and configure the address of mysql, as shown below:

Copy

  • Run the qmake command, specifying the paths of MySQL header files and library files, for example:

INCLUDEPATH += "E:/mysql/mysql-5.7.27-winx64/include"
DEPENDPATH += "E:/mysql/mysql-5.7.27-winx64/include"
LIBS += "E:/mysql/mysql-5.7.27-winx64/lib/libmysql.lib"
DESTDIR = ../mysql/mylib

Copy

  • Run the make or mingw32-make command, and select the appropriate command according to your compiler type (if you use sql in the VS environment, you only need to compile under the VS compiler), for example:
mingw32-make

Copy

  • If the compilation is successful, you will see a file named qsqlmysql.dll in the current directory, which is the QMysql plug-in. You need to copy this file to the qt/plugins/sqldrivers folder under the Qt directory where you run the Qt application, for example:
F:\QT\5.12.9\msvc2017_64\plugins\sqldrivers

The above is our preparation work:

Then it is how to use the Qmysql function in QT; first, we need to import the header file first, the file is as follows:

#include <QtSql/QSqlDatabase>	// 连接数据库
#include <QtSql/QSqlError>		// 数据库连接失败打印报错语句
#include <QtSql/QSqlQuery>		// 数据库操作(增删改查)
#include <QSqlQueryModel>

I defined the function name to write in the cpp file:

 Q_OBJECT
public:
    mysql(QWidget *parent);
    ~mysql();
    void insert(QString InserName,int id,QString symbol,QString value);
    void insert_line(QString InserName,QString id,QString symbol,QString value,QString v,QString despoitory);

    void data_connect(bool,bool);//连接数据库
    void data_test_connect(QStringList);//测试能否成功连接数据库
    void close_data();
    void creat_table(QString TableName);//创建一个表
    void update_table(QString InserName,QString id,QString key,QString value);//更新数据库
    void delete_table(QString TableName,QString id);//删除数据库
    void find_alltable(QString datebase);//查找所有数据路表格
    void find_table_inf(QString TableName);//查询某个表中的数据
    void find_table_row(QString TableName,QString row_name,QString col_name);//查询表中某一行的数据
    void find_table_col(QString TableName,QString col_name);//表名,列名
    void find_table_desposite(QString TableName,QString col_name);//表名,列名查询储位名

In the corresponding function name, the functions implemented are as follows:

The first is to connect to the database part of the function

QSettings *myini=new QSettings("info.ini", QSettings::IniFormat);//构造QSettings对象,访问ini文件
        QStringList info_digitial={"digitial_type","hostname","port","database_name","user_name","password"};
        QStringList s;
        //设置键值对
        s.clear();
        myini->beginGroup("digital");
        for(int i=0;i<info_digitial.size();i++)
        {
           s.append(myini->value(info_digitial[i]).toString());
        }
        myini->endGroup();
        delete myini;
    //输出可用数据库
        qDebug()<<"available drivers:";
        QStringList drivers = QSqlDatabase::drivers();
        foreach(QString driver, drivers)
        qDebug()<<driver;//输出中含有MySQL,那么恭喜你说明你的qt有MySQL驱动了

        QSqlDatabase db = QSqlDatabase::addDatabase(s[0]);
        db.setHostName(s[1]);
        db.setPort(s[2].toInt());
        db.setDatabaseName(s[3]);//数据库名
        db.setUserName(s[4]);//用户名
        db.setPassword(s[5]);//密码
        bool ok = db.open();//打开并连接数据库
        if(message_prompt)
        {
            if (ok){
                QMessageBox::information(this, "infor", "success connect");
            }
            else {
                QMessageBox::information(this, "infor", "open failed");
                qDebug()<<"error open database because"<<db.lastError().text();
            }
        }

Here I get the database settings by reading the information stored in the ini file, which mainly includes: 

Define a QSqlDatabase object db, instantiate it, if it can connect successfully, it will return a Boolean value, here I use this bool value to judge whether it is successfully connected to the database.

Then create a table in the database and insert values ​​into it:


    QSqlQuery query;
    QString sql=QString("create table %1(订单号 text, 料号 text, 品名 text, 数量 text,储位 text);").arg(TableName);//"订单号","料号","品名","数量"
    qDebug()<<"SQL"<<sql;

    //创建表是否成功

    if (!query.exec(sql))//.exec(),作用是开启一个循环,执行一个事件,相当于while(1)

    {
        qDebug() << QString::fromLocal8Bit("creat table failed:") << query.lastError();

    }

    else

    {
        qDebug() << QString::fromLocal8Bit("creat table success!");

    }

The function of inserting data into the table table is implemented as follows:

 QSqlQuery query;
       QString str=QString("insert into %4(序号,标签,value) values(%1,'%2','%3')").arg(id).arg(symbol).arg(value).arg(InserName);
       if(query.exec(str)==false)
       {
            qDebug() << "insert failed";
            QMessageBox::warning(this,u8"数据插入错误",u8"请检查数据是否正确");
       }
       else
       {
           QMessageBox::information(this, "insert", "insert connect");
            qDebug() <<"insert success";
       }

The function of updating data is realized, and the code part is as follows:

    QSqlQuery query;
    QString updata = QString("update %1 set  %2='%3' where 订单号='%4'").arg(InserName).arg(column).arg(value).arg(row);
    qDebug()<<"--update--"<<updata;
    if (!query.exec(updata))
    {
        qDebug() << QString::fromLocal8Bit("updata failed!") << query.lastError();
    }
    else
    {
        qDebug() << QString::fromLocal8Bit("updata success!");
    }

Earlier we mentioned how to create a database table and implement the function of inserting data. Next, let’s talk about the sight of the database’s delete function. The code part is as follows:

     QSqlQuery query;
     QString sql = QString("delete from %1 where  订单号 = '%2'").arg(TableName).arg(id);
     if(query.exec(sql))
     {
         qDebug()<<"delete success!";
     }
     else
     {
         qDebug()<<"delete failed!";
     }

Guess you like

Origin blog.csdn.net/Helloorld_1/article/details/132297907