本文介绍了如何在android中的sqlite中批量插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用SQLiteOpenHelper进行数据插入.我需要插入2500个ID和2500个名称,因此需要太多时间.请任何人帮助我如何减少插入时间.我们可以一次插入多个记录吗?任何人都可以帮助我.先感谢您.代码:
I am using SQLiteOpenHelper for data insertion. I need to insert 2500 id and 2500 names, So it takes too much time. Please any one help me how to reduce the insertion time. can we insert multiple records at a time ? any one help me. thank you in advance.code:
public class DatabaseHandler extends SQLiteOpenHelper {
SQLiteDatabase db;
private static final int DATABASE_VERSION = 8;
private static final String TABLE_CITY = "CITYDETAILS";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CITY );
String CREATE_CITY_TABLE = "CREATE TABLE " + TABLE_CITY + "("
+ CityId + " INTEGER," + CityName + " TEXT " + ")";
db.execSQL(CREATE_CITY_TABLE);
db.execSQL(CREATE_RechargeTypes_TABLE);
this.db=db;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
// Create tables again
onCreate(db);
}
public void add_city(String cityid,String cityname){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues values = new ContentValues();
values.put(CityId, cityid);
values.put(CityName, cityname);
db.insert(TABLE_CITY, null, values);
db.insertWithOnConflict(TABLE_CITY, null, values, SQLiteDatabase.CONFLICT_IGNORE);
db.setTransactionSuccessful();
db.endTransaction();
}
}
活动评估:
try{
String Status = result.get("Status").getAsString();
if (TextUtils.equals(Status, "true")) {
Gson gson = new Gson();
JsonArray array = result.get("data")
.getAsJsonArray();
Type type = new TypeToken<ArrayList<Cities>>() {
}.getType();
setmCities((ArrayList<Cities>) gson.fromJson(array, type));
for(int i=0;i< array.size();i++) {
db.add_city(mCities.get(i).getCityid(),mCities.get(i).getCityname());
}
}
推荐答案
使用事务插入所有行-每个事务都不插入一行.
Use a transaction to insert all the rows -- NOT one row per transaction.
SQLiteDatabase db = ...
db.beginTransaction();
try {
// do ALL your inserts here
db.setTransactionSuccessful()
} finally {
db.endTransaction();
}
编辑
public void add_cities(List<Cities> list) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
for (Cities city : list) {
values.put(CityId, city.getCityid());
values.put(CityName, city.getCityName());
db.insert(TABLE_CITY, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
所有插入,一次交易.
这篇关于如何在android中的sqlite中批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!