是一个嵌入式数据库,占资源少,支持关系型数据库。Android系统采用了此数据库,有关操作的类有sqliteDatabase 和接口sqliteOpenHelper。建立应用程序与sqlite的连接,以及对其库中数据操作关键代码如下:
1、//实现接口sqliteOpenHelper的类 ,其中的构造函数
public DatabaseHelper(Context context,String name,CursorFactory factory,
int version) {
super(context,name,factory,version);
// TODO Auto-generated constructor stub
}
2、//重写onCreate函数
public void onCreate(sqliteDatabase db) {
// TODO Auto-generated method stub
db.execsql("create table user(id int,name varchar(20))");
}
class CreateOnClick implements OnClickListener
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getReadableDatabase();
}
}
class UpdateOnClick implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db",null,2);
sqliteDatabase db = dbHelper.getReadableDatabase();
}
}
5、插入数据表数据的关键代码
class InsertOnClick implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put("id",1);
values.put("name","zhao");
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.insert("user",values);
}
class DeleteOnClick implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.delete("user","name='zhao'",null);
System.out.println("record delete");
}
}
class UpdatingOnClick implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put("name","zhangsan");
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.update("user",values,"id=?",new String[]{"1"});
}
}
class QueryOnClick implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db"); sqliteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query ("user",new String[]{"id","name"},new String[]{"1"},null); while(cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); System.out.print("query----->" + name); } } }