QML学习笔记2(sqlite3数据库)

//sqlitehelper.h
#ifndef SQLITEHELPER_H
#define SQLITEHELPER_H

#include <QObject>
#include <QDir>
#include <QDebug>

#include "sqlite3.h"

class SQLiteHelper{

public:
    SQLiteHelper();
    ~SQLiteHelper();
    int getIntValue(char **data, int totalcol, int selectrow,int selectcol);
    QString getQStringValue(char **data, int totalcol, int selectrow,int selectcol);
    sqlite3 *sqldb=nullptr;
};

#endif // SQLITEHELPER_H
//sqlitehelper.cpp
#include "sqlitehelper.h"

SQLiteHelper::SQLiteHelper()
{
    QString Filepath;
    //Filepath =QCoreApplication::applicationDirPath();//exe应用程序位置
    Filepath =QDir::currentPath();//项目位置
    const char* path="/data";//保存数据库文件的文件夹
    const QString temp= Filepath+path;//保存数据库文件的完整路径
    QDir dir(temp);
    if(!dir.exists())
    {
        //如果不存在路径则创建
        dir.mkpath(temp);
    }
    QString fullpath=temp+"/test.db";//包含数据库文件名的完整路径
    int res = sqlite3_open(fullpath.toStdString().c_str(), &sqldb);//打开数据库
    if(res != 0)//打开失败
    {
        qDebug()<<"打开数据库失败:"<<sqlite3_errcode(sqldb)<<endl;
        qDebug()<<"打开数据库失败:"<<sqlite3_errmsg(sqldb)<<endl;
    }
    else
    {
        //        char *errmsg;      //出错信息
        //        const char *createPerson="create table IF NOT EXISTS Person("
        //                                 "ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
        //                                 "Name varchar(30) NOT NULL, "
        //                                 "Age int NOT NULL"
        //                                 ");";
        //        res = sqlite3_exec(sqldb, createPerson, NULL, NULL, &errmsg);
        //        if(res!=SQLITE_OK)
        //        {
        //            qDebug()<<"创建Person表失败:"<<sqlite3_errcode(sqldb)<<endl;
        //            qDebug()<<"创建Person表失败:"<<sqlite3_errmsg(sqldb)<<endl;
        //            qDebug()<<"创建Person表失败:"<<errmsg;
        //            sqlite3_free(errmsg);
        //        }
    }
}

SQLiteHelper::~SQLiteHelper()
{
    qDebug()<<"close sqlite";
    int res = sqlite3_close(sqldb);
    if(res!=SQLITE_OK)
    {
        qDebug()<<sqlite3_errcode(sqldb)<<endl;
        qDebug()<<sqlite3_errmsg(sqldb)<<endl;
    }
}

QString SQLiteHelper::getQStringValue(char **data, int totalcol, int selectrow, int selectcol)
{
    return data[(selectrow+1)*totalcol+selectcol];
}
int SQLiteHelper::getIntValue(char **data, int totalcol, int selectrow,int selectcol)
{
    return atoi(data[(selectrow+1)*totalcol+selectcol]);
}


猜你喜欢

转载自blog.csdn.net/dwm88888888/article/details/131326609