如何在android中的sqlite中批量插入

时间:2015-08-19 06:31:42

标签: android sqlite sqliteopenhelper

我正在使用SQLiteOpenHelper进行数据插入。我需要插入2500个id和2500个名字,所以需要花费太多时间。请任何人帮我如何减少插入时间。我们可以一次插入多个记录吗?任何人帮助我。先感谢您。 代码:

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

                }
            }

5 个答案:

答案 0 :(得分:41)

使用事务插入所有行 - 每个事务不是一行。

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

所有插入,一次交易。

答案 1 :(得分:4)

谢谢@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;
        }
    }

答案 2 :(得分:2)

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

答案 3 :(得分:0)

将您的查询放在string.xml中的字符串数组中,使用资源处理程序在代码中打开它们并在循环中执行它们。在循环之前使用beginTransaction()和entTransaction()方法来回滚案例失败时的更改。

答案 4 :(得分:0)

这个答案来晚了,但是我可以帮助其他人以简单的方式插入很多行 有一种方法可以插入很多行 让我们创建要插入的值(根据您的值添加循环)

public String getMultiInsertValues(){
      StringBuilder valueToInsert = new StringBuilder()
//start loop
      valueToInsert.append("(")
      valueToInsert.append(id)
      valueToInsert.append("),")
      valueToInsert.append("(")
      valueToInsert.append(name)
      valueToInsert.append("),")
//end of the loop      
      valueToInsert.deleteCharAt(valueToInsert.lastIndexOf(","))
      valueToInsert.append(";")
      return valueToInsert.toString()
}

然后我们将该值添加到sql

    String sql = "INSERT INTO " + tableName + " ( id ) VALUES \n" + valueToInsert 
    //value to Insert from the last function

最后我们应该执行此sql

SQLiteDatabase db = getWritableDatabase();
db.execSQL(sql);
注意,在sqLite中有最大的变量和术语条件,您应该将值除以500,并使用上述解决方案插入每500个值,因为会有多个SQL查询,我建议您使用{{1 }}就像其他答案中提到的一样