码迷,mamicode.com
首页 > 数据库 > 详细

QT 创建本地数据库(SQLite数据库)存储数据

时间:2019-12-06 13:52:31      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:bool   ini   fine   注意   exe   app   col   clu   sql   

 

注意:QT自带SQLITE数据库,不需要再安装

 

1.创建一个包含创建、查询、修改和删除数据库的数据库类(DataBase)

DataBase.h头文件

#pragma once

#include <QObject>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlError>
#include "client_global.h"

struct StudentData
{
  QString name;
  int score;
  QString grade;
}; class DataBase : public QObject { Q_OBJECT public: DataBase(QString name,QObject *parent=0); ~DataBase();
public:
bool insertData(StudentData data); bool deleteData(int name); bool getDataByName(int name, StudentData & data); bool getDataList(QList<StudentData> & list);
   bool update();
private: QSqlDatabase m_DataBase; private: bool initTable(); bool isExistTable(QString table); bool createTable(QString table); };

 

DataBase.cpp源文件

#include "XDataBase.h"
#include <QCoreApplication>
#include <QDebug>
#include <QSqlRecord>


DataBase::DataBase(QString name, QObject *parent)
    : QObject(parent)
{
    
    if (QSqlDatabase::contains(name)) {

        m_DataBase = QSqlDatabase::database(name);
    }
    else {

        m_DataBase = QSqlDatabase::addDatabase("QSQLITE");
        m_DataBase.setDatabaseName(name+".db");
        m_DataBase.setDatabaseName(QCoreApplication::applicationDirPath()+"//"+ name);
    }
    initTable();
}

DataBase::~DataBase()
{
}

bool DataBase::initTable()
{
    if (!m_DataBase.open()) {
        return false;
    }

    if (!isExistTable("students")) {
        createTable("students");
    }
    return false;
}

bool DataBase::isExistTable(QString table)
{
    bool bRet = false;
    if (!m_DataBase.open()) {
        return bRet;
    }
    QSqlQuery query(m_DataBase);
    query.exec(QString("select count(*) from sqlite_master where type=‘table‘ and name=‘%1‘").arg(table));    //关键的判断      
    if (query.next())
    {
        if (query.value(0).toInt() > 0)
        {
            bRet = true;
        }
    }
    return false;
}

bool DataBase::createTable(QString table)
{
    if (!m_DataBase.open()) {
        return false;
    }

    QSqlQuery query(m_DataBase);
    if (table == QString("students")) {

        bool success = query.exec("CREATE TABLE students ("
                                    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                                    "name VARCHAR(40) NOT NULL, "
                                    "score INTEGER NOT NULL, "
                                    "grade VARCHAR(40) NOT NULL)");

        if (success) {
            return true;   //新建数据库成功
        }
        else {
            QSqlError lastError = query.lastError();
            QString err = lastError.driverText();
            return false;
        }
    }
    else {
        return false;
    }
}

bool DataBase::insertData(StudentData data)
{
    if (!m_DataBase.open()) {
        return false;
    }
    QSqlQuery query(m_DataBase);

    bool success = query.exec(QString("INSERT INTO students (name, score,class) "
        "VALUES (%1, %2, %3)").arg(data.name)
                              .arg(data.score)
                              .arg(data.grade));
        
    if (!success) {

        QSqlError lastError = query.lastError();
        QString err = lastError.driverText();
        return false;
    }
    return true;
}

bool DataBase::deleteData(QString name)
{
    if (!m_DataBase.open()) {
        return false;
    }
    QSqlQuery query(m_DataBase);
    query.prepare(QString("DELETE FROM students WHERE name=‘%1‘").arg(name));
    query.exec();
    return false;
}

bool DataBase::getDataByName(int name, StudentData & data)
{
    if (!m_DataBase.open()) {
        return false;
    }
QSqlQuery query(m_DataBase); query.prepare(QString(
"SELECT * FROM students WHERE name=‘%1‘").arg(name)); query.exec(); QSqlRecord rec = query.record(); if (query.next()) { data.name = query.value(0).toString(); data.score = query.value(1).toInt(); data.grade = query.value(2).toString(); return true; } return false; } bool DataBase::getDataList(QList<StudentData>& list) { if (!m_DataBase.open()) { return false; } QSqlQuery query(m_DataBase); query.prepare(QString("SELECT * FROM students")); query.exec(); QSqlRecord rec = query.record(); while (query.next()) { StudentData data; device.name = query.value(0).toInt(); device.score = query.value(1).toString(); device.grade = query.value(2).toInt(); list.append(data); return true; } return false; } bool DataBase::update() { if (!m_DataBase.open()) { return false; } QSqlQuery query(m_DataBase); query.prepare("UPDATE students SET score = 100 , name = ‘小A‘"); query.exec(); return false; }

 

 

 

调用:

XClientApp.h头文件

#pragma once

#include <QApplication>
#include <DataBase.h>
#include "ServerAPI.h"
#define clientApp static_cast<XClientApp*>(QCoreApplication::instance())

class XClientApp : public QApplication
{
    Q_OBJECT

public:
    XClientApp(int argc, char *argv[]);
    ~XClientApp();
    DataBase* getDataBase();
    ServerAPI* getServerAPI();
    QString getAppName();
private:
    void setFont(QString font);
    void setStyle();
private:
    DataBase* m_pDataBase;
    ServerAPI* m_pServerAPI;
signals:
    void sglSystemMessage(QString type, QString data);
};

 

 

XClientApp.cpp源文件

 

#include "XClientApp.h"

XClientApp::XClientApp(int argc, char *argv[])
    : QApplication(argc, argv)
{
    
     m_pDataBase = new DataBase("xclient", this);
     setWindowIcon(QIcon(":/Images/Resources/朱砂古镇.ico"));//可执行程序图标
     setStyle();
     m_pServerAPI = new ServerAPI(this);   //注意有重载
}

DataBase * XClientApp::getDataBase()   //获取本地数据库并进行操作
{
    return m_pDataBase;
}

 

 

QT 创建本地数据库(SQLite数据库)存储数据

标签:bool   ini   fine   注意   exe   app   col   clu   sql   

原文地址:https://www.cnblogs.com/tingtaishou/p/11994480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!