Ionic 3中SQLite批量插入优化:现有代码运行过慢
优化Ionic 3 SQLite批量插入速度的解决方案
兄弟,我太懂你这种批量插入卡到怀疑人生的感觉了!你现在的代码问题在于:每次循环都单独调用executeSql,SQLite每执行一次单条插入都会自动开启、提交一次事务,这会产生巨量的磁盘IO开销,数据量稍大速度直接拉胯。
解决核心思路就是用SQLite事务包裹所有插入操作,把所有插入打包成一次提交,能把速度提升几十甚至上百倍。下面是优化后的完整方案:
基础优化版(事务包裹循环插入)
insertQuotationBatch(value: any[]) { // 开启事务,所有插入操作都在这个事务上下文里执行 this.database.transaction(tx => { // 遍历数据,用事务对象tx执行插入 value.forEach(item => { const data = [ item.quotation_id, item.customer_name, item.product_name, item.price, item.services, item.response_time, item.created_time ]; const sql = `INSERT INTO care_plan_quotation_history( care_plan_quotation_id, customer_name, product, price, services, response_time, created_time ) VALUES(?, ?, ?, ?, ?, ?, ?)`; // 重点:用tx.executeSql而非this.database.executeSql,确保操作属于同一事务 tx.executeSql(sql, data); }); }) .then(() => { console.log('批量插入成功!'); // 这里可以添加插入成功后的业务逻辑 }) .catch(error => { console.error('批量插入失败:', error); // 处理错误逻辑,比如回滚提示等 }); }
进阶优化版(合并多条插入为单条SQL)
如果数据量特别大(比如上千条),可以把多个VALUES合并成一条INSERT语句,进一步减少SQL执行次数,速度还能再提一档:
insertQuotationBatch(value: any[]) { if (value.length === 0) return; // 生成对应数量的占位符组 const placeholders = value.map(() => '(?, ?, ?, ?, ?, ?, ?)').join(','); const sql = `INSERT INTO care_plan_quotation_history( care_plan_quotation_id, customer_name, product, price, services, response_time, created_time ) VALUES ${placeholders}`; // 把所有数据平铺成一维数组,匹配占位符顺序 const data = value.flatMap(item => [ item.quotation_id, item.customer_name, item.product_name, item.price, item.services, item.response_time, item.created_time ]); this.database.transaction(tx => { tx.executeSql(sql, data); }) .then(() => console.log('超大批量插入成功')) .catch(err => console.error('插入失败:', err)); }
关键优化点说明
- 事务的作用:
this.database.transaction()会创建一个事务上下文,所有内部的tx.executeSql操作都会被打包,只有全部执行完成后才会一次性提交到数据库,避免了频繁开启/提交事务的磁盘IO开销。 - 用事务对象执行SQL:必须使用回调里的
tx对象执行SQL,而不是直接调用this.database.executeSql,这样才能保证所有操作属于同一个事务。 - 合并SQL的注意事项:单条SQL有长度限制,如果数据量过万可能需要分批次合并,避免触发SQLite的单语句长度上限。
内容的提问来源于stack exchange,提问作者NITISH
相关产品推荐
相关产品推荐

