1. 说明:

本文章在QML中搭建一个简易的界面,大致的功能:点击左侧对应的按钮,会调用后端 C++ 函数去对数据库进行操作,并在右侧的 ListView 区域实时的显示数据库中的数据状态。利用此简易 demo 简要介绍数据库的基本操作方法。
运行效果:

2. 相关方法:

本文中对数据库的操作,包括基本的查询、插入、更改、删除四种指令,仅介绍本文中用到的方法,实际数据库的操作指令有很多,在其他文章中会详细介绍

2.1 sql 查询语句
select * from 表名;		//(基础查询)查询对应表中的所有内容
select 字段名1,字段名2,... from 表名;		//(基础查询)查询表中对应字段中的内容
select *(字段名1,字段名2,...) from 表名 where 条件;	//(条件查询)

在这个博文中QML连接数据库已经介绍了创建 mysql 自定义类,并连接了数据库。在此基础上,更改其中的成员函数为 selectAllData(),相关代码如下:
mysql.h:

Q_INVOKABLE void selectAllData();

mysql.cpp:

//查询数据
void MySql::selectAllData()
{
    QSqlQuery query;
    query.prepare(QString("SELECT * FROM friends;"));
    if(query.exec()){
        while (query.next()) {
            int id = query.value("friendsID").toInt();
            QString name = query.value("friendsName").toString();
            int age = query.value("friendsAge").toInt();

            emit sendQueryInfo(id,name,age);
        }

    }
}
2.2 sql 插入语句
insert into 表名 values(字段值1,字段值2,...)	//向表中插入新数据,并未指定字段,则按照字段顺序写入字段值
insert into 表名(字段1,字段2,...) values(字段值1,字段值2,...)	// 插入指定字段的字段值数据

mysql.h:

Q_INVOKABLE void insertData();

mysql.cpp:

//插入新数据
void MySql::insertData()
{
    QSqlQuery query;

    query.exec(QString("insert into friends(friendsName,friendsAge) values('xiaozheng',60);"));
    //插入新数据后,发射信号,告诉视图进行更新
    emit updateView();

}
2.3 sql 删除语句
delete from 表名 where 条件;		//按照某种条件删除数据

mysql.h:

Q_INVOKABLE void deleteData();

mysql.cpp:

//删除数据
void MySql::deleteData()
{
    QSqlQuery query;

    query.exec(QString("delete from friends where friendsID = (select friendsID from friends order by friendsID desc limit 1);"));
    //删除数据后,发射信号,告诉视图进行更新
    emit updateView();
}
2.4 sql 更改语句
update 表名 set 字段1 = 新值,字段2 = 新值,... where 条件;		//按照某条件更改数据内容

mysql.h:

Q_INVOKABLE void updateData();

mysql.cpp:

//更改数据
void MySql::updateData()
{
    QSqlQuery query;

    query.exec(QString("update friends set friendsName = 'new_Name' where friendsID = (select friendsID from friends order by friendsID desc limit 1);"));
    //删除数据后,发射信号,告诉视图进行更新
    emit updateView();
}

3. 整体代码:

mysql.h:

#ifndef MYSQL_H
#define MYSQL_H

#include <QObject>

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlField>
#include <QSqlRecord>

#include <QDebug>



class MySql : public QObject
{
    Q_OBJECT
public:
    explicit MySql(QObject *parent = 0);
    ~MySql();
    bool init();
    bool closeSql();

    Q_INVOKABLE void selectAllData();
    Q_INVOKABLE void insertData();
    Q_INVOKABLE void deleteData();
    Q_INVOKABLE void updateData();


signals:
	//信号:发送查询到的数据
    void sendQueryInfo(int mID,QString mName,int mAge);
    //信号:通知QML更新视图
    void updateView();
private:
    QSqlDatabase db;

};

#endif // MYSQL_H

mysql.cpp:

#include "mysql.h"

MySql::MySql(QObject *parent) : QObject(parent)
{
    init();
}

MySql::~MySql()
{
    closeSql();
}

bool MySql::init()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("自己的数据库文件路径");
    if(db.open()){
        return true;
    }
    return db.open();
}

bool MySql::closeSql()
{
    db.close();
    return false;
}

//查询数据
void MySql::selectAllData()
{
    QSqlQuery query;
    query.prepare(QString("SELECT * FROM friends;"));
    if(query.exec()){
        while (query.next()) {
            int id = query.value("friendsID").toInt();
            QString name = query.value("friendsName").toString();
            int age = query.value("friendsAge").toInt();

            emit sendQueryInfo(id,name,age);
        }

    }
}

//插入新数据
void MySql::insertData()
{
    QSqlQuery query;

    query.exec(QString("insert into friends(friendsName,friendsAge) values('xiaozheng',60);"));
    //插入新数据后,发射信号,告诉视图进行更新
    emit updateView();

}

//删除数据
void MySql::deleteData()
{
    QSqlQuery query;

    query.exec(QString("delete from friends where friendsID = (select friendsID from friends order by friendsID desc limit 1);"));
    //删除数据后,发射信号,告诉视图进行更新
    emit updateView();
}

//更改数据
void MySql::updateData()
{
    QSqlQuery query;

    query.exec(QString("update friends set friendsName = 'new_Name' where friendsID = (select friendsID from friends order by friendsID desc limit 1);"));
    //删除数据后,发射信号,告诉视图进行更新
    emit updateView();
}

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "mysql.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    //注册 MySql 自定义类到 QML 的上下文背景中进行使用
    MySql mysql;
    engine.rootContext()->setContextProperty("mySql",&mysql);
    
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.0

ApplicationWindow {
    id:rootWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    function refreshDataModel(){
        dataModel.clear()
        mySql.selectAllData()
    }

	//接收 C++ 端发送过来的信号
    Connections{
        target: mySql
        onSendQueryInfo:{
            dataModel.append({id:mID,name:mName,age:mAge})
        }
        onUpdateView:{
            refreshDataModel()
        }
    }

    Rectangle{
        id:btnRect
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.bottom: parent.bottom
        width: 200
        color: "#8496A2"
        Column{
            anchors.fill: parent
            spacing: 5
            padding: 2
            Row{
                height: 30
                spacing: 2
                Button{
                    width: 50
                    height: 30
                    text:"查询"
                    onClicked: {
                        refreshDataModel()
                    }
                }
                Button{
                    width: 70
                    height: 30
                    text:"插入新数据"
                    onClicked: {
                        mySql.insertData()
                    }
                }
                Button{
                    width: 70
                    height: 30
                    text:"删除数据"
                    onClicked: {
                        mySql.deleteData()
                    }
                }
            }
            Row{
                height: 30
                spacing: 5
                Button{
                    width: 70
                    height: 30
                    text:"更改数据"
                    onClicked: {
                        mySql.updateData()
                    }
                }
            }

        }

    }


    Rectangle{
        anchors.top: parent.top
        anchors.left: btnRect.right
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        color: "#627480"
        ListView{
            id:dataView
            anchors.fill: parent
            spacing:5
            clip: true
            header:Rectangle{
                width: parent.width - 10
                height: 20
                anchors.horizontalCenter: parent.horizontalCenter
                color: Qt.rgba(1.0,1.0,1.0,0.0)

                Text{
                    id:idHeader
                    width: 25
                    height: 25
                    anchors.left: parent.left
                    anchors.leftMargin: 10
                    text:"ID"
                }
                Text{
                    width: 25
                    height: 25
                    anchors.horizontalCenter: parent.horizontalCenter
                    text:"Name"
                }
                Text{
                    width: 25
                    height: 25
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    text:"Age"
                }
            }

            model: ListModel{
                id:dataModel
            }
            delegate: Rectangle{
                id:dataDelegate
                width: parent.width - 10
                anchors.horizontalCenter: parent.horizontalCenter
                height: 20
                color: Qt.rgba(1.0,1.0,1.0,0.0)
                border.color: "white"
                border.width: 1
                radius: 10
                Text{
                    id:friendsID
                    text: id
                    anchors.left: parent.left
                    anchors.leftMargin: 11
                }
                Text{
                    id:friendsName
                    text:name
                    anchors.horizontalCenter: parent.horizontalCenter
                }
                Text{
                    id:friendsAge
                    text: age
                    anchors.right: parent.right
                    anchors.rightMargin: 16
                }
            }
        }

    }
}

持续更新中,请大家多多关注…