.h文件
class SqlThread : public QThread
{
Q_OBJECT
public:
SqlThread(QString threadName, sqlite3* db);
~SqlThread();
void setMessage(const QString &message);
QString getMessage();
void stop();
QString getThreadName();
int pushData(std::string sqlData);//提供给外部接口(仅支持:插入或删除数据)
protected:
void run();
private:
volatile bool stopped;
QMutex mutex;
QMutex mutex1;
QString m_szThreadName;
sqlite3 *m_pDb;
QString m_szMessage;
std::vector<std::string> m_OutSqlVec; //存sql语句
};
.cpp文件
SqlThread::SqlThread(QString threadName, sqlite3* db)
{
m_szThreadName = threadName;
m_pDb = db;
stopped = false;
}
SqlThread::~SqlThread()
{
m_OutSqlVec.clear();
}
void SqlThread::setMessage(const QString &message)
{
m_szMessage = message;
}
QString SqlThread::getMessage()
{
qDebug() << "sql thread is alive. message:" << m_szMessage;
return m_szMessage;
}
void SqlThread::stop()
{
qDebug() << m_szThreadName << "线程退出";
stopped = true;
}
QString SqlThread::getThreadName()
{
return m_szThreadName;
}
/**
* @func: pushData
* @brief: 提供给外部接口的函数,提供数据库插入和删除
* @author: xxx
* @param: sqlData: sql语句
* @return: 是否加到了队列里
*/
int SqlThread::pushData(std::string sqlData)
{
if (sqlData != "")
{
mutex.lock();
m_OutSqlVec.push_back(sqlData);
mutex.unlock();
return 0;
}
else
{
return -1;
}
}
/**
* @func: run
* @brief: 线程run函数
* @author: xxx
* @param: void
* @return: void
*/
void SqlThread::run()
{
forever
{
if (stopped)
{
stopped = false;
break;
}
if (m_OutSqlVec.size() == 0)
{
sleep(1);
}
//qDebug() << "sql thread is running.";
//进行数据存储操作
std::vector<std::string> SqlVec; //sql语句
if (m_OutSqlVec.size() > 0)
{
mutex.lock();
std::copy(m_OutSqlVec.begin(), m_OutSqlVec.end(), std::back_inserter(SqlVec));
m_OutSqlVec.clear();
mutex.unlock();
}
if (SqlVec.size() > 1)
{
SqliteExec(m_pDb, "BEGIN TRANSACTION");
qDebug() << "执行语句共:" << SqlVec.size();
for (int i = 0; i < SqlVec.size(); i++)
{
std::string szsql = SqlVec[i];
//int rc = sqlite3_exec(m_pDb, (char*)szsql.c_str(), NULL, NULL, 0);
int rc = SqliteExec(m_pDb, (char*)szsql.c_str());
if (rc != SQLITE_OK)
{
qDebug() <<StrToQStr(SqlVec[i].c_str()) << "执行失败";
}
}
int nRet = SqliteExec(m_pDb, "END TRANSACTION");
if (nRet != SQLITE_OK)
{
printf("sql insert fail-------%d\n", nRet);
}
}
SqlVec.clear();
}
}
调用该线程 //我做的时候是放在单例类里做的,当时还自己给自己埋了个坑,在单例列的析构里执行了delete sqlThread,但是没有赋值NULL,这就导致下一次想创建线程就不行了,因为线程指针已经是随机的了。
if (db_ && sqlThread == NULL)
{
qDebug() << "创建线程 sql thread.";
sqlThread = new SqlThread("sql thread", db_);
sqlThread->start();
}
在其他地方调用:
char buf[500];
sprintf(buf, "delete from setting where name = '%s' and address = '%s'", pied->name_, pframe->m_table->item(i, 2)->text().toUtf8().data());
单例类::Instance()->sqlThread->pushData(buf);