Ale*_*u D 5 sql transactions cordova typescript ionic-framework
我有一个大约17 MB的txt文件,我必须解析,逐行拆分,然后使用事务将其添加到数据库中.如果文件太大而我尝试打开它,应用程序将耗尽内存,所以我尝试将其分片读取然后将每个片段导入数据库.由于交易,在DB中输入的数据不正确.使用的代码有一部分:
await file_reader.resolveLocalFilesystemUrl(path + file).then(async (file_entry: any) => {
await file_entry.file(async (file) => {
let reader = new FileReader();
reader.onprogress = async (reader_result: any) => {
let loaded = _.cloneDeep(reader_result.loaded);
let total = _.cloneDeep(reader_result.total);
let is_last_element: boolean = _.cloneDeep(loaded == total);
let i: number = 0;
let document_length = this.sync_parser.getReaderLength();
let event_type: number = this.sync_parser.getEventType();
content = iconv.encode(reader.result, encoding).toString();
await this.db.db.transaction(async (database: any) => {
while (document_length >= i) {
if (event_type == SyncParserIo.START_TAG) {
this.table = await this.newHeader(this.sync_parser.getName());
} else if (event_type == SyncParserIo.END_TAG) {
// this.file_content = null;
} else if (event_type == SyncParserIo.ROW) {
// here I execute basic_update_insert function
}
event_type = this.sync_parser.next(i);
i++;
}
}).then(()=>{
this.logger.info(this.TAG, "End document from transaction");
}).catch((e)=>{
//log
});
if (is_last_element) {
resolve(true);
}
};
await reader.readAsBinaryString(file);
});
}).catch((e) => {
this.logger.error("FileSystem Error", e.message);
return reject(e);
});
protected basic_update_insert(table, rows_map, where, where_bindings, database?) {
let db_query = database != null ? database : this.database;
let update_query_util: any = DbUtil.update(table, rows_map, where, where_bindings);
let insert_query_util: any = DbUtil.insert(table, rows_map);
this.import_result = null;
db_query.executeSql(update_query_util.query, update_query_util.bindings, (tx, res) => {
if (res.rowsAffected === 0) {
tx.executeSql(insert_query_util.query, insert_query_util.bindings, (tx2, insert_result) => {
if (insert_result.insertId != null) {
this.import_result = ImporterIo.RESULT_OK;
}
}, (e) => {
this.import_result = ImporterIo.ERROR_INSERT_ROW;
});
} else if (res.rowsAffected === 1) {
this.import_result = ImporterIo.RESULT_OK;
} else if (res.rowsAffected > 1) {
this.import_result = ImporterIo.RESULT_OK;
}
}, (e) => {
this.logger.error(this.TAG, `error from ${table} update`, e);
this.import_result = ImporterIo.ERROR_UPDATE_ROW;
});
}
Run Code Online (Sandbox Code Playgroud)
您可能会发现cordova-sqlite-porter很有用(有一个Ionic Native Typescript 包装器)。它包装了 SQLite DB API,允许您向其传递格式化为 SQL 语句或 JSON 的数据转储。
对于如此大量的数据,将数据转换为插件支持的 JSON 结构可能符合您的兴趣,因为它将 JSON 转换为批量插入,在插件示例项目中,这会在导入时带来可观察到的性能改进数据速度快 100 倍。
或者,您可能希望手动重新编写 SQL INSERT 语句,以利用此答案中概述的UNION SELECT 优化。
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |