我正在使用SQLiteOpenHelper進行數據插入。我需要插入2500個ID和2500個名字,所以需要太多時間。請任何人幫助我如何減少插入時間。我們可以一次插入多個記錄嗎?任何人都可以幫助我。先謝謝你。 代碼:如何在android中的sqlite批量插入
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();
}
}
活動CALSS:
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());
}
}
我已經這樣做了。請參閱「void add_city」 –
@kartheekij您每插入一行只有一行。我說的是在同一個事務中插入所有的行。 – Karakuri
這是db類,在我的活動類中,我發送像db.add_city(cityid,cityname)這樣的json數據;像這樣...所以我會得到所有的記錄...但它需要太多時間來插入。 –