Android中SQLite使用

  • 内容
  • 评论
  • 相关

现在的主流移动设备像Android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动设备上的SQLite开发技巧。对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。

package com.gaoxueping;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.activity_main);
		SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
		db.execSQL("DROP TABLE IF EXISTS person");
		db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
		
		Person person = new Person();
		person.name = "gavin";
		person.age = 25;
		
		db.execSQL("INSERT INTO person VALUES (NULL, ? ,?)", new Object[]{person.name, person.age});
		
		person.name = "nameForKey";
		person.age = 24;
		ContentValues cv = new ContentValues();
		cv.put("name", person.name);
		cv.put("age", person.age);
		db.insert("person", null, cv);
		
		cv = new ContentValues();
		cv.put("age", 23);
		db.update("person", cv, "name = ?", new String[]{"gavin"});
		
		Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"23"});
		while(c.moveToNext()){
			int _id = c.getInt(c.getColumnIndex("_id"));
			String name = c.getString(c.getColumnIndex("name"));
			int age = c.getInt(c.getColumnIndex("age"));
			Log.i("db", "_db=>" + _id + ",name=>" + name + ",age=>" + age);
		}
		c.close();
		db.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

person.java

package com.gaoxueping;

public class Person {
	public int _id;
	public String name;
	public int age;
	public String info;
	
	public Person(){};
	
	public Person(String name, int age, String info){
		this.name = name;
		this.age = age;
		this.info = info;
	}
}

完整项目下载地址
http://pan.baidu.com/s/1kTK95Kb

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注