------------------------------
代码的分割线---------------------------
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 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 ");
int columnNum = 0;
for (String colName : columns) {
sql.append((columnNum > 0) ? "," : "");
++columnNum;
}
columnNum = 0;
for (int i = 0; i < columns.length; i++) {
sql.append((i > 0) ? ",?" : "?");
++columnNum;
}
sqliteStatement statement = db.compileStatement(sql.toString());
while (dataSource.next()) {
dataSource.bindAllValues(statement);
if (statement.executeInsert() != -1) {
++succCnt;
} else {
}
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;
}
}