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中插入数据时,使用批量插入的方式可以大大提高插入速度。

批量插入的模板如下:

public void inertOrUpdateDateBatch(List<String> sqls) {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		try {
			for (String sql : sqls) {
				db.execSQL(sql);
			}
			// 设置事务标志为成功,当结束事务时就会提交事务
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 结束事务
			db.endTransaction();
			db.close();
		}
	}
注意此处的:

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只能有一条语句。在执行的时候,不能写成:

insert into student values('yang','boy');insert into student values('zhou','girl');
形式,而需要将两条 SQL语句拆开,每条SQL语句执行一次。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值