是一个嵌入式数据库,占资源少,支持关系型数据库。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))");
}
3、创建数据库的关键代码
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();
}
}
4、更新数据库的关键代码
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", null, values);
}
6、删除数据表数据的关键代码
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");
}
}
7、更新数据表数据的关键代码
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"});
}
}
8、查询数据表中数据的关键代码
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"}, "id=?", new String[]{"1"}, null, null, null);
while(cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex("name"));
System.out.print("query----->" + name);
}
}
}