QT次线程连接数据库
今天使用Qt的次线程来连接数据库
思路: 1.初始化的时候首先调用次线程初始化数据库 2.初始化QSqlTabelModel等 3.使用到数据库的地方要验证数据库句柄,如果已失效,要再次调用次线程.
遇到一些问题
1.connect不识别QSqlDatabase类型,要使用qRegisterMetaType注册. 2.如果使用了QSqlTableModel,要在数据库连接成功后初始化.
头文件
#ifndef THREAD_H #define THREAD_H #include <QThread> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlError> #include "config.h" class Thread : public QThread { Q_OBJECT public: Thread(); ~Thread(); void stop(); QSqlDatabase dbhandle; bool correct; QString returncode; signals: void execresult(QSqlDatabase db,bool correct = true,QString returncode = ""); protected: void run(); }; #endif // THREAD_H
源文件
#include "thread.h" Thread::Thread() { this->correct = false; this->returncode = ""; } void Thread::run() { dbhandle = QSqlDatabase::addDatabase("QMYSQL"); dbhandle.setHostName(DB_ADDR); dbhandle.setUserName(DB_USER); dbhandle.setPassword(DB_PASS); dbhandle.setPort(DB_PORT); dbhandle.setDatabaseName(DB_DB); if(dbhandle.open()) this->correct = true; else { this->correct = false; this->returncode = dbhandle.lastError().text(); } this->stop(); } void Thread::stop() { emit execresult(dbhandle,correct,returncode); } Thread::~Thread() { }
槽函数
void Cafes_Income::init_db_return(QSqlDatabase db, bool correct, QString errorstr) { initdbdialog->close(); if(!correct) { QMessageBox::information(this,tr("数据库初始化失败!"),errorstr); exit(EXIT_FAILURE); } this->dbhandle = db; }
使用数据库的地方
if(!dbhandle.isValid()) this->init_database_link();
init_database_link
/* * 名称:init_database_link * 作用:初始化数据库链接 * 参数:no * 返回:void */ void Cafes_Income::init_database_link() { if(!dbhandle.isOpen()) { this->initdb->start(); initdbdialog->exec(); } }