2015-08-19 61 views
14

我正在使用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()); 

       } 
      } 

回答

31

使用事務插入的所有行 - 每次交易不要一行。

SQLiteDatabase db = ... 
db.beginTransaction(); 
try { 
    // do ALL your inserts here 
    db.setTransactionSuccessful() 
} finally { 
    db.endTransaction(); 
} 

EDIT

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(); 
    } 
} 

所有插入,一個事務。

+0

我已經這樣做了。請參閱「void add_city」 –

+1

@kartheekij您每插入一行只有一行。我說的是在同一個事務中插入所有的行。 – Karakuri

+0

這是db類,在我的活動類中,我發送像db.add_city(cityid,cityname)這樣的json數據;像這樣...所以我會得到所有的記錄...但它需要太多時間來插入。 –

0

將您的查詢放入string.xml中的字符串數組中,使用資源處理程序在代碼中打開它們並在循環中執行它們。在循環之前,使用beginTransaction()和entTransaction()方法在發生故障時回滾更改。

2

謝謝@karakuri。 我將城市ID和城市名稱列表傳遞給add_city函數,並通過該列表循環並插入所有數據。由此我們可以在少量時間內將數據插入數據庫。

數據庫類:

public void add_cities(ArrayList<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(); 
     } 
    } 

數據類:

public class Cities { 
    public String getCityid() { 
     return cityid; 
    } 

    public void setCityid(String cityid) { 
     this.cityid = cityid; 
    } 

    public String getCityname() { 
     return cityname; 
    } 

    public void setCityname(String cityname) { 
     this.cityname = cityname; 
    } 

    @Expose 

    private String cityid="0"; 

    @Expose 
    private String cityname=""; 

    public Cities(){ 
    } 

} 

活動類:

ArrayList<Cities> mCities; 
    protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_splash); 
      db = new DatabaseHandler(getApplicationContext()); 
      executeCircleAndOperatorsList(); 

     } 
     void executeCircleAndOperatorsList() { 
    db.ClearTables(); 
      ServiceClient serviceClient = ServiceUtil.getServiceClient(); 
      JsonParser jsonParser = new JsonParser(); 

      mCitiesCallback = new CancelableCallback(citiescallback); 

      serviceClient.getCities("getCities_v1", mCitiesCallback); 
    } 
    Callback<JsonObject> citiescallback=new Callback<JsonObject>() { 

      @Override 
      public void success(final JsonObject jsonObject, Response response) { 
       Thread t=new Thread(new Runnable() { 
        @Override 
        public void run() { 
         parsecities(jsonObject); 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show(); 

           Intent intent=new Intent(SplashActivity.this,LoginAcivtiy.class); 
           startActivity(intent); 
          } 
         }); 
        } 
       }); 
       t.start(); 

      } 

      @Override 
      public void failure(RetrofitError error) { 

      } 
     }; 
     public void parsecities(JsonObject result) { 
      //Log.v("TAG_RESULT", "" +result.toString()); 
      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)); 
        long start = System.currentTimeMillis(); 
        db.add_cities(mCities); 

        System.out.println(System.currentTimeMillis() - start); 
        circle_list=db.get_cities(); 
        Log.v("TAG_CIRCLELIST",""+circle_list); 



       } 
       else if (TextUtils.equals("Status", "false")) { 

        // showToast(operators.getMessage()); 

       } else { 
        throw new JSONException("Something went wrong "); 
       }  }catch(Exception e){ 
       e.printStackTrace(); 

      } 

     } 
     public void setmCities(ArrayList<Cities> mCities) { 
      this.mCities = mCities; 
     } 
    } 
+0

數據庫被鎖定。你如何解決數據庫鎖定問題? –

0

嘗試SQLiteStatement不僅僅是更快的BeginTransaction
在2-3倍()

public void add_cities(ArrayList<Cities> list) { 
    SQLiteDatabase database = this.getWritableDatabase(); 
    String sql = "INSERT INTO " + TABLE_NAME + " VALUES(?, ?)"; 
    SQLiteStatement statement = database.compileStatement(sql); 
    database.beginTransaction(); 
    try { 
     for (Cities c : list) { 
      statement.clearBindings(); 
      statement.bindLong(1, c.getCityId()); 
      statement.bindLong(2, c.getCityName()); 
      statement.execute(); 
     } 
     database.setTransactionSuccessful(); 
    } finally { 
     database.endTransaction(); 
    } 
}