日期:2014-05-16  浏览次数:20542 次

SQLite 数据库增删改查 完整例子
                                  SQLite 数据库增删改查 完整例子

1)编写实体类:Employee,代码如下所示:

/*
* Copyright (C) Mesada Technologies Co., Ltd. 2005-2011.
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Mesada Technologies Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement
* you entered into with Mesada.
*/
package com.mesada.database.demo;

import android.net.Uri;

/**
* 一个实体类
*
* @author Xiaolong Long
* @date 2011-3-10
* @version 1.0
*/
public class Employee {
private int id;
private String name;
private int age;

/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id
*            the id to set
*/
public void setId(int id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the age
*/
public int getAge() {
return age;
}

/**
* @param age
*            the age to set
*/
public void setAge(int age) {
if (age >= 1 && age < 150) {
this.age = age;
} else {
this.age = -1;
}
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}

2)新建类DBAdapter类,封装了操作数据库的增删改查,打开,关闭数据库的功能,代码如下:
package com.mesada.database.demo;

/*
* Copyright (C) Mesada Technologies Co., Ltd. 2005-2011.
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Mesada Technologies Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement
* you entered into with Mesada.
*/

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

/**
* Please specify the function of this class
*
* @author Xiaolong Long
* @date 2011-3-10
* @version 1.0
*/
public class DBAdapter {

private static final String DB_NAME = "mesada.db";
private static final String DB_TABLE = "employee";
private static final int DB_VERSION = 1;

// many columns
public static final String ID = "_id";
public static final String NAME = "name";
public static final String AGE = "age";

private SQLiteDatabase mDb;
private final Context mContext;
private DBOpenHelper mDBOpenHelper;

public DBAdapter(Context context) {
this.mContext = context;
}


/**
*
* Open the datab