#include "thread.h"
#include <QVector>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv)
QVector<Thread*>vector
Thread *thread
//创建多个线程,并start
for(int i=0i<10i++){
thread=new Thread
vector.append(thread)
thread->set(i)
thread->start()
}
//等待所有线程执行完,然后删除线程
foreach(thread,vector){
thread->wait()
}
foreach(thread,vector){
delete thread
}
return a.exec()
}
-------------------------------------------------------------------------------------------------
#include "thread.h"
Thread::Thread(QObject *parent) : QThread(parent)
{
}
void Thread::run()
{
begin()
}
//为每个线程创建一个连接名
void Thread::set(int a)
{
connectionName=QString::number(a)
}
void Thread::connectionDatabase(QString dbName)
{
QSqlDatabasedb=QSqlDatabase::addDatabase("QMYSQL",connectionName)
db.setHostName("localhost")
db.setDatabaseName(dbName)
db.setUserName("root")
db.setPassword("")
if(!db.open())
qDebug()<<"db open fail"
}
void Thread::begin()
{
QString dbName="learnsql"
connectionDatabase(dbName)
QSqlDatabase db=QSqlDatabase::database(connectionName)
db.transaction()//开启事物
QSqlQuery query(db)
//向表student中插入10000条数据
for(int i=1i<=10000i++){
query.exec("insert into student values(1)")
}
db.commit()//提交事物
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)