QSqlite遇到的问题


问题:QSqlDatabasePrivate::database: requested database does not belong to the calling thread.
原因:在主线程中创建了数据库,初始化了表结构,然后子线程中直接使用数据库,查资料发现不能这样干。
解决办法:网上提到使用线程池,或者在子线程中重新创建数据库连接,我采用的第二种,因为数据库操作很少。

问题:QSqlQuery::exec: database not open QSqlError("", “Driver not loaded”, “Driver not loaded”)
原因:好像是需要绑定数据库。
现象:在主线程中不需要绑定,在子线程中不绑定就有这个问题。
解决办法:在请求数据的时候,QSqlQuery query(QSqlDatabase db)的方式初始化绑定。

下面提交一个主/子线程调用代码

主线程
do{
	QSqlDatabase sqliteDB = QSqlDatabase::addDatabase("QSQLITE","SELFSQLITE");
	sqliteDB.setDatabaseName("box6604.db");
	if (!sqliteDB.open()){
	    qCritical("Failed to connect SqliteDatabase");
	    return;
	}
	qInfo("Succeed to connect SqliteDatabas");
	do{
		//执行其他操作
		QSqlQuery sql_query;			//这里不用绑定
		QString sql_content(R"(create table if not exists XX(id int primary key))");
		if(!sql_query.exec(sql_content)){
			qCritical("Fail to create table XX");
		}
		qInfo("Succeed to create table XX");
	}while(0);
}while(0);
QSqlDatabase::removeDatabase("SELFSQLITE");
子线程
do{
	QSqlDatabase sqliteDB = QSqlDatabase::addDatabase("QSQLITE","SELFSQLITE");
	sqliteDB.setDatabaseName("box6604.db");
	if (!sqliteDB.open()){
	    qCritical("Failed to connect SqliteDatabase");
	    return;
	}
	qInfo("Succeed to connect SqliteDatabas");
	do{
		//执行其他操作
		QSqlQuery sql_query(sqliteDB);			//这里必须绑定
		QString sql_content(R"(create table if not exists XX(id int primary key))");
		if(!sql_query.exec(sql_content)){
			qCritical("Fail to create table XX");
		}
		qInfo("Succeed to create table XX");
	}while(0);
}while(0);
QSqlDatabase::removeDatabase("SELFSQLITE");
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值