【问题标题】:QThread to send large queries to the databaseQThread 向数据库发送大型查询
【发布时间】:2009-02-11 13:01:25
【问题描述】:

我创建了这个继承自 QThread 的类,用于向数据库服务器发送数据,你怎么看?可以改进吗?

谢谢

#ifndef QUERYTHREAD_H
#define QUERYTHREAD_H

#包括

类 QSqlQuery;

类查询线程:公共 QThread {
    公共插槽:
        bool exec(QSqlQuery *query, Priority priority=InheritPriority);
    受保护:
        虚空运行();
    私人的:
        布尔 m_hasError;
        QSqlQuery *q;
};

#endif // QUERYTHREAD_H
#include "querythread.h"

#包括
#包括

bool QueryThread::exec(QSqlQuery *query, Priority 优先级)
{
    q=查询;
    开始(优先级);
    while(isRunning()) qApp->processEvents();
    返回 m_hasError;
}

无效查询线程::运行()
{ m_hasError=q->exec(); }

【问题讨论】:

    标签: qt4


    【解决方案1】:

    几点意见:

    exec 中的 while 循环消除了拥有单独线程的优势。您应该在构造函数中传入查询,每个查询有一个线程,不要覆盖exec,宁愿只使用start 并使用信号异步报告任何错误。

    您还应该按值传递 QSqlQuery 或将其存储在托管指针中,例如 std::auto_ptr(或 C++11 的 std::unique_ptr)。许多 Qt 类是 implicitly shared(虽然不是这个),但托管指针可以为您提供异常安全性。

    就个人而言,我会简单地做这样的事情

    class Query : public QThread {
    
        QSqlQuery m_query;
        // I prefer values unless there's a particular reason to use pointers.
    
    public:
    
        Query (const QSqlQuery & query)
        : m_query (query)
        {
        }
    
        void run ()
        {
            emit finished (m_query .exec ());
            deleteLater ();
        }
    
    public signals:
    
        void finished (bool);
    };
    
    Query * q = new Query ("SELECT foo FROM bar");
    
    connect (q, SIGNAL (finished (bool), ...);
    
    q -> start ();
    

    【讨论】:

      猜你喜欢
      • 2013-01-04
      • 1970-01-01
      • 2023-03-18
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      相关资源
      最近更新 更多