如题,在 worker 里面 beginTransation 会有异常,执行失败,但用 c 层开启了子线程查询并没有出现异常,测试代码如下
// 创建数据库 config 对象
static napi_value OpenDB(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value argv[1] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// 获取函数argv[1],此为为rawfile相对路径
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[0], strBuf, sizeof(strBuf), &strSize);
std::string dirName(strBuf, strSize);
std::cout << "dir is" << dirName << std::endl;
const char* your_dataBaseDir = dirName.c_str();
const char* your_storeName = "RdbTest.db";
const char* your_bundleName = "com.example.ndk";
const char* your_moduleName = "entry";
bool your_isEncrypt = false; // 或者true,根据你的需求
int your_securityLevel = OH_Rdb_SecurityLevel::S1; // 根据你的需求设置
int your_area = RDB_SECURITY_AREA_EL1; // 根据你的需求设置
OH_Rdb_Config oh_rdb_config = {
.selfSize = sizeof(OH_Rdb_Config),
.dataBaseDir = your_dataBaseDir,
.storeName = your_storeName,
.bundleName = your_bundleName,
.moduleName = your_moduleName,
.isEncrypt = your_isEncrypt,
.securityLevel = your_securityLevel,
.area = your_area
};
int errCode = 0;
// 获取获取OH_Rdb_Store实例
OH_Rdb_Store *store_ = OH_Rdb_GetOrOpen(&oh_rdb_config, &errCode);
char createTableSql[] = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, "
"AGE INTEGER, SALARY REAL, CODES BLOB)";
// 执行建表语句
OH_Rdb_Execute(store_, createTableSql);
// 创建键值对实例
OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket();
valueBucket->putText(valueBucket, "NAME", "Lisa");
valueBucket->putInt64(valueBucket, "AGE", 188);
valueBucket->putReal(valueBucket, "SALARY", 100.5);
uint8_t arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
valueBucket->putBlob(valueBucket, "CODES", arr, len);
// 插入数据
int rowId = OH_Rdb_Insert(store_, "EMPLOYEE", valueBucket);
// 开启线程开启事务查询
std::thread mythread([=]() {
int64_t age;
int transactionId = OH_Rdb_BeginTransaction (store_);
OH_Predicates *predicates = OH_Rdb_CreatePredicates("EMPLOYEE");
const char *columnNames[] = {"NAME", "AGE"};
int len = sizeof(columnNames) / sizeof(columnNames[0]);
OH_Cursor *cursor = OH_Rdb_Query(store_, predicates, columnNames, len);
int columnCount = 0;
cursor->getColumnCount(cursor, &columnCount);
// OH_Cursor是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始
while (cursor->goToNextRow(cursor) == OH_Rdb_ErrCode::RDB_OK) {
cursor->getInt64(cursor, 1, &age);
}
OH_Rdb_Commit (store_);
// 释放谓词实例
predicates->destroy(predicates);
// 释放结果集
cursor->destroy(cursor);
});
mythread.detach();
// 销毁键值对实例
valueBucket->destroy(valueBucket);
napi_value num;
napi_create_double(env, rowId, &num);
return num;
}
目前不能并发操作事务,开启事务和提交事务要在同一个线程中,并且此时另一个线程不能并发的再去开启事务和提交事务。