批量插入
这是一次插入大块数据的示例。你要插入的所有数据都收集在 ContentValues 数组中。
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
int count = 0;
String table = null;
int uriType = IChatContract.MessageColumns.uriMatcher.match(uri);
switch (uriType) {
case IChatContract.MessageColumns.MESSAGES:
table = IChatContract.MessageColumns.TABLE_NAME;
break;
}
mDatabase.beginTransaction();
try {
for (ContentValues cv : values) {
long rowID = mDatabase.insert(table, " ", cv);
if (rowID <= 0) {
throw new SQLException("Failed to insert row into " + uri);
}
}
mDatabase.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
count = values.length;
} finally {
mDatabase.endTransaction();
}
return count;
}
以下是如何使用它的示例:
ContentResolver resolver = mContext.getContentResolver();
ContentValues[] valueList = new ContentValues[object.size()];
//add whatever you like to the valueList
resolver.bulkInsert(IChatContract.MessageColumns.CONTENT_URI, valueList);