標籤:
1、通過一次編譯跟事務來最佳化資料庫插入,通過僅查詢指定欄位來最佳化資料庫查詢。
/** * <ol><li>開啟資料庫 * <li>建立句子(避免String+String) * <li>編譯(避免多次編譯) * <li>執行 * <li>關閉資料庫</ol> * @author shixin */public class MainActivity extends Activity {List<String> list = new LinkedList<String>();ArrayAdapter<String> arrayAdapter;SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ListView listView = (ListView) findViewById(R.id.listView);arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);listView.setAdapter(arrayAdapter);//Create a memory backed SQLite database. Its contents will be destroyed when the database is closeddb = SQLiteDatabase.create(null);//Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns datadb.execSQL("create table life (plant text, animal text)");}@Overrideprotected void onDestroy() {super.onDestroy();db.close();}public void onClick(View v){switch (v.getId()) {case R.id.btn_insert:try {db.beginTransaction();String[][] lifes = {{"potato", "tomato", "apple"}, {"rat", "cat", "dog"}};SQLiteStatement stmt = db.compileStatement("insert into life values(?,?)");for(int i=0;i<lifes[0].length;i++){stmt.clearBindings();stmt.bindString(1, lifes[0][i]);stmt.bindString(1, lifes[1][i]);stmt.executeInsert();}db.setTransactionSuccessful();} catch (Exception e) {}finally{db.endTransaction();}break;case R.id.btn_query://只查詢需要的欄位效率更高Cursor c = db.query("life", new String[]{"plant"}, null, null, null, null, null);while(c.moveToNext()){list.add(c.getString(c.getColumnIndex("plant")));}c.close();//讓ListView更新顯示arrayAdapter.notifyDataSetChanged();}}}
Android資料庫的最佳化