Android批量插入数据

移动开发 Android
本文通过全方位的介绍和讲解为读者朋友们呈现出了Android批量插入数据的实现方法,解决了以往的上万次插入操作速度慢的问题,大大提高了插入速度。

Android中在sqlite插入数据的时候默认一条语句就是一个事务(All individual SQL Statements, (with rare exceptions like Bulk Inserts with No Log, or Truncate Table) are automaticaly "In a Transaction" whether you explicitly say so or not.. (even if they insert, update, or delete millions of rows).),因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知。因此在Android中插入数据时,使用批量插入的方式可以大大提高插入速度。

批量插入的模板如下:

  1. public void inertOrUpdateDateBatch(List<String> sqls) {   
  2.         SQLiteDatabase db = getWritableDatabase();   
  3.         db.beginTransaction();   
  4.         try {   
  5.             for (String sql : sqls) {   
  6.                 db.execSQL(sql);   
  7.             }   
  8.             // 设置事务标志为成功,当结束事务时就会提交事务   
  9.             db.setTransactionSuccessful();   
  10.         } catch (Exception e) {   
  11.             e.printStackTrace();   
  12.         } finally {   
  13.             // 结束事务   
  14.             db.endTransaction();   
  15.             db.close();   
  16.         }   
  17.     } 

注意此处的:

  1. db.execSQL(sql);   

官方的API显示:

public void execSQL (String sql)

Added in API level 1

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use insert(String, String, ContentValues)update(String, ContentValues, String, String[]), et al, when possible.

When using enableWriteAheadLogging(), journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using enableWriteAheadLogging()

Parameters
sql the SQL statement to be executed. Multiple statements separated by semicolons are not supported.
Throws
SQLException if the SQL string is invalid

说明,每次执行SQL只能有一条语句。在执行的时候,不能写成:

  1. insert into student values('yang','boy');insert into student values('zhou','girl');   

形式,而需要将两条SQL语句拆开,每条SQL语句执行一次。

责任编辑:闫佳明 来源: csdn
相关推荐

2021-04-08 10:55:53

MySQL数据库代码

2011-08-04 18:00:47

SQLite数据库批量数据

2021-09-27 07:56:41

MyBatis Plu数据库批量插入

2021-02-01 00:04:13

Dictionary数据批量

2010-09-03 11:47:38

SQL删除

2022-09-29 10:06:56

SQLMySQL服务端

2010-09-01 16:26:11

SQL删除批量

2023-12-30 20:04:51

MyBatis框架数据

2010-09-08 16:53:43

SQL查询循环

2021-10-09 06:59:36

技术MyBatis数据

2009-07-20 17:03:55

批量插入数据ASP.NET

2013-09-22 10:25:23

MySQLSQL性能优化

2020-11-23 10:50:27

MySQLSQL数据库

2022-09-23 09:44:17

MyBatisforeach

2018-08-09 08:59:56

数据库MySQL性能优化

2021-09-14 13:15:43

MySQL数据库脚本

2021-06-28 10:25:47

MySQL数据库重复数据

2021-11-02 14:46:50

数据

2023-09-24 14:39:10

MySQLPostgreSQL

2011-08-04 15:07:24

点赞
收藏

51CTO技术栈公众号