我正在使用以下代码将数据插入表中。
public CourseDB addcourseByType(CourseDB rmdb) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COURSE_NAME, rmdb.getcourse_name());
values.put(CATEGORY_COURSE_TYPE, rmdb.getcategory_course_type());
values.put(COURSE_CRS, rmdb.getcourse_crs());
values.put(CATEGORY_ID_FOR, rmdb.getcat_foreign_id()); // Contact
db.insert(TABLE_COURSE, null, values);
String selectQuery = "SELECT " + COURSE_ID + " FROM "
+ TABLE_COURSE + " WHERE " + COURSE_CRS + "='"
+ rmdb.getcourse_crs() + "'" + " AND " + CATEGORY_ID_FOR
+ "='" + rmdb.getcat_foreign_id() + "'";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
rmdb.setcourse_id(Integer.parseInt(cursor.getString(0)));
} while (cursor.moveToNext());
}
cursor.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
return rmdb;
}
请让我知道是否有任何方法可以更改代码以更快地添加值,我JSON
从文件中获取格式数据,将其存储为数组并将其传递给上述方法。
阿斯米塔
我尝试了这些建议,并且能够将插入时间从 16 秒减少到 11 秒。请看看我的新代码。是否可以进一步减少。
// //convert string to JSONArray
JSONArray jArray = new JSONArray(bufferString);
if (bufferString.isEmpty()) {
} else {
db.deleteAllCourseByTypeDB(type);
}
boolean eventFlag = false;
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
ContentValues values = new ContentValues();
for (int j = 0; j < jArray.length(); j++) {
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(j);
String crsCd = (json_data.getString("crsCd"));
String crsTitle = (json_data.getString("crsTitle"));
System.out.println("Time for one JSON parsing "+(System.currentTimeMillis()-insideStart));
try
{
values.put(COURSE_NAME, crsTitle); values.put(CATEGORY_COURSE_TYPE, type); // Contact
// Name
values.put(COURSE_CRS, crsCd);
values.put(CATEGORY_ID_FOR, id_notebook2); // Contact
sqlDB.insert(TABLE_COURSE, null, values);
//Error in between database transaction
}
finally {
}
System.out.println("Time for one One Looping "+(System.currentTimeMillis()-insideStart));
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
long endTime = System.currentTimeMillis();
System.out.println("this is my timer "+(endTime-startTime)/1000);
} catch (FileNotFoundException e) { } catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}