标签:
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; @Override protected 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 closed db = SQLiteDatabase.create(null); //Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data db.execSQL("create table life (plant text, animal text)"); } @Override protected 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(); } } }
标签:
原文地址:http://blog.csdn.net/talk2soul/article/details/45936847