加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite批量插入Android代码示例

发布时间:2020-12-12 19:38:03 所属栏目:百科 来源:网络整理
导读:参考之前博文: 《如何向SQLite批量插入大量记录和其他一些使用心得》 ------------------------------代码的分割线--------------------------- import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; public c
参考之前博文: 《如何向SQLite批量插入大量记录和其他一些使用心得》 ------------------------------代码的分割线--------------------------- import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement;
public class SQLiteBatchUpdateTool {
private static final String TAG = "SQLiteBatchUpdateTool";
public static interface BatchOperateDataSource { public int size(); public boolean next(); public void bindAllValues(SQLiteStatement statement); }
public static boolean batchInsertOrUpdate(String logMsg, SQLiteHelper helper,String table,String[] columns, BatchOperateDataSource dataSource) { if (dataSource == null || dataSource.size() <= 0) { return false; // 没有数据无需更新 } if (columns == null || columns.length <= 0) { Log.e(TAG,logMsg + "传入的列值不正确,不能构造sql"); return false; } Log.i(TAG,logMsg + "开始:记录数=" + dataSource.size()); long start = System.currentTimeMillis(); long failedCnt = 0; long succCnt = 0; boolean result = false; try { synchronized (helper) { SQLiteDatabase db = helper.getWritableDatabase(); try { db.beginTransaction(); StringBuilder sql = new StringBuilder(); sql.append("INSERT OR REPLACE INTO "); sql.append(table); sql.append('(');
int columnNum = 0; for (String colName : columns) { sql.append((columnNum > 0) ? "," : ""); sql.append(colName); ++columnNum; } sql.append(')'); sql.append(" VALUES ("); columnNum = 0; for (int i = 0; i < columns.length; i++) { sql.append((i > 0) ? ",?" : "?"); ++columnNum; } sql.append(')');
SQLiteStatement statement = db.compileStatement(sql.toString()); while (dataSource.next()) { dataSource.bindAllValues(statement); if (statement.executeInsert() != -1) { ++succCnt; } else { ++failedCnt; } statement.clearBindings(); } result = true; db.setTransactionSuccessful (); } catch (Exception e) { Log.e(TAG,logMsg + "执行数据库操作异常",e); result = false; } finally { if (db != null) { try { db.endTransaction(); } catch (Exception e) { Log.e(TAG,logMsg + "结束数据库事务异常",e); } try { db.close(); } catch (Exception e) { Log.e(TAG,logMsg + "关闭数据库异常",e); } } } } } finally { Log.i(TAG,logMsg + "结束:耗时=" + (System.currentTimeMillis() - start) + "ms,更新成功=" + succCnt + ",更新失败=" + failedCnt); } return result; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读