频道栏目
IT货架 > > 正文
Android数据库的优化
网友分享于:Jan 1, 1970 8:00:00 AM    来源: IT货架   

标签:

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

Android数据库的优化

标签:

相关板块推荐 iPhone WindowsPhone

广告服务联系QQ:1134687142 | 网站地图

版权所有: IT货架- 内容来自互联网,仅供用于技术学习,请遵循相关法律法规. 京ICP备11030978号-1