我的上一篇博客讲的是简单的 android SQLite 数据库的基本操作如增删改查,有兴趣的朋友可以点一下这里android 简单SQLite数据库 增删改查
但是呢,一般的项目里,一个数据库也不会只有一个数据表,常常是多个数据表共同管理的,这个时候应该怎么搭建项目的数据库操作代码框架呢?
光说不练假把式,动手开一个Demo
首先,在项目里建立起三个文件夹,分别是 app 、 db 、 model
app 文件夹下存放继承 Application 的 MyApplication 类
db 文件夹下存放 数据库操作类
model 文件夹下存放 数据实体类
在 model 文件夹下创建 实体类 PhoneBean
/**
* 手机实体类
* @author dlong
* created at 2019/3/13 11:34 AM
*/
public class PhoneBean {
/** 数据库自增ID */
public int id;
/** 手机品牌 */
public String brand;
/** 手机型号 */
public String model;
/** 手机价格 */
public int price;
/**
* 转化成字符串
* @return
*/
public String toString(){
StringBuilder builder = new StringBuilder("[");
builder.append(id).append("--");
builder.append("品牌:").append(brand).append("--");
builder.append("型号:").append(model).append("--");
builder.append("价格:").append(price).append("]");
return builder.toString();
}
}
在 model 文件夹下创建 实体类 CompanyBean
/**
* 公司实体类
* @author dlong
* created at 2019/3/13 11:37 AM
*/
public class CompanyBean {
/** 数据库自增ID */
public int id;
/** 公司名称 */
public String name;
/** 公司CEO */
public String ceo;
/** 公司建立年份 */
public int year;
public String toString(){
StringBuilder builder = new StringBuilder("[");
builder.append(id).append("--");
builder.append("公司名称:").append(name).append("--");
builder.append("CEO:").append(ceo).append("--");
builder.append("创立年份:").append(year).append("年]");
return builder.toString();
}
}
在 db 文件夹下建立一个 DBConfig 用于记录数据库配置信息
/**
* 数据库配置信息
* @author dlong
* created at 2019/3/13 11:27 AM
*/
public class DBConfig {
/** 数据库名称 */
public static final String DB_NAME = "multiple_test.db";
/** 数据库版本 */
public static final int DB_VERSION = 1;
/**
* 判断数据表是否为空
* @param db
* @param tablename
* @return
*/
public static boolean HaveData(SQLiteDatabase db, String tablename){
Cursor cursor;
boolean a = false;
cursor = db.rawQuery("select name from sqlite_master where type='table' ", null);
while(cursor.moveToNext()){
//遍历出表名
String name = cursor.getString(0);
if(name.equals(tablename)){
a = true;
}
Log.i("System.out", name);
}
if(a){
cursor = db.query(tablename,null,null,null,null,null,null);
//检查是不是空表
return cursor.getCount() > 0;
}else {
return false;
}
}
}
在 db 文件夹下建立一个 PhoneDBDao 用于操作数据表
/**
* 手机数据表操作类
* @author dlong
* created at 2019/3/13 11:39 AM
*/
public class PhoneDBDao {
/** 数据表名称 */
public static final String TABLE_NAME = "phone_info";
/** 表的字段名 */
public static String KEY_ID = "id";
public static String KEY_BRAND = "brand";
public static String KEY_MODEL = "model";
public static String KEY_PRICE = "price";
private SQLiteDatabase mDatabase;
/** 上下文 */
private Context mContext;
/** 数据库打开帮助类 */
private DBMaster.DBOpenHelper mDbOpenHelper;
public PhoneDBDao(Context context) {
mContext = context;
}
public void setDatabase(SQLiteDatabase db){
mDatabase = db;
}
/**
* 插入一条数据
* @param phone
* @return
*/
public long insertData(PhoneBean phone) {
ContentValues values = new ContentValues();
values.put(KEY_BRAND, phone.brand);
values.put(KEY_MODEL, phone.model);
values.put(KEY_PRICE, phone.price);
return mDatabase.insert(TABLE_NAME, null, values);
}
/**
* 删除一条数据
* @param id
* @return
*/
public long deleteData(int id) {
return mDatabase.delete(TABLE_NAME, KEY_ID + "=" + id, null);
}
/**
* 删除所有数据
* @return
*/
public long deleteAllData() {
return mDatabase.delete(TABLE_NAME, null, null);
}
/**
* 更新一条数据
* @param id
* @param phone
* @return
*/
public long updateData(int id, PhoneBean phone) {
ContentValues values = new ContentValues();
values.put(KEY_BRAND, phone.brand);
values.put(KEY_MODEL, phone.model);
values.put(KEY_PRICE, phone.price);
return mDatabase.update(TABLE_NAME, values, KEY_ID + "=" + id, null);
}
/**
* 查询一条数据
* @param id
* @return
*/
public List<PhoneBean> queryData(int id) {
if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
return null;
}
Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
KEY_BRAND,
KEY_MODEL,
KEY_PRICE},
KEY_ID + "=" + id , null, null, null, null);
return convertUtil(results);
}
/**
* 查询所有数据
* @return
*/
public List<PhoneBean> queryDataList() {
if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
return null;
}
Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
KEY_BRAND,
KEY_MODEL,
KEY_PRICE},
null, null, null, null, null);
return convertUtil(results);
}
/**
* 查询结果转换
* @param cursor
* @return
*/
private List<PhoneBean> convertUtil(Cursor cursor) {
int resultCounts = cursor.getCount();
if (resultCounts == 0 || !cursor.moveToFirst()) {
return null;
}
List<PhoneBean> mList = new ArrayList<>();
for (int i = 0; i < resultCounts; i++) {
PhoneBean phone = new PhoneBean();
phone.id = cursor.getInt(cursor.getColumnIndex(KEY_ID));
phone.brand = cursor.getString(cursor.getColumnIndex(KEY_BRAND));
phone.model = cursor.getString(cursor.getColumnIndex(KEY_MODEL));
phone.price = cursor.getInt(cursor.getColumnIndex(KEY_PRICE));
mList.add(phone);
cursor.moveToNext();
}
return mList;
}
}
在 db 文件夹下建立一个 CompanyDBDao 用于操作数据表
/**
* 公司数据表操作类
* @author dlong
* created at 2019/3/13 11:46 AM
*/
public class CompanyDBDao {
/** 数据表名称 */
public static final String TABLE_NAME = "company_info";
/** 表的字段名 */
public static String KEY_ID = "id";
public static String KEY_NAME = "name";
public static String KEY_CEO = "ceo";
public static String KEY_YEAR = "year";
private SQLiteDatabase mDatabase;
/** 上下文 */
private Context mContext;
/** 数据库打开帮助类 */
private DBMaster.DBOpenHelper mDbOpenHelper;
public CompanyDBDao(Context context) {
mContext = context;
}
public void setDatabase(SQLiteDatabase db){
mDatabase = db;
}
/**
* 插入一条数据
* @param company
* @return
*/
public long insertData(CompanyBean company) {
ContentValues values = new ContentValues();
values.put(KEY_NAME, company.name);
values.put(KEY_CEO, company.ceo);
values.put(KEY_YEAR, company.year);
return mDatabase.insert(TABLE_NAME, null, values);
}
/**
* 删除一条数据
* @param id
* @return
*/
public long deleteData(int id) {
return mDatabase.delete(TABLE_NAME, KEY_ID + "=" + id, null);
}
/**
* 删除所有数据
* @return
*/
public long deleteAllData() {
return mDatabase.delete(TABLE_NAME, null, null);
}
/**
* 更新一条数据
* @param id
* @param company
* @return
*/
public long updateData(int id, CompanyBean company) {
ContentValues values = new ContentValues();
values.put(KEY_NAME, company.name);
values.put(KEY_CEO, company.ceo);
values.put(KEY_YEAR, company.year);
return mDatabase.update(TABLE_NAME, values, KEY_ID + "=" + id, null);
}
/**
* 查询一条数据
* @param id
* @return
*/
public List<CompanyBean> queryData(int id) {
if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
return null;
}
Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
KEY_NAME,
KEY_CEO,
KEY_YEAR},
KEY_ID + "=" + id , null, null, null, null);
return convertUtil(results);
}
/**
* 查询所有数据
* @return
*/
public List<CompanyBean> queryDataList() {
if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
return null;
}
Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
KEY_NAME,
KEY_CEO,
KEY_YEAR},
null, null, null, null, null);
return convertUtil(results);
}
/**
* 查询结果转换
* @param cursor
* @return
*/
private List<CompanyBean> convertUtil(Cursor cursor) {
int resultCounts = cursor.getCount();
if (resultCounts == 0 || !cursor.moveToFirst()) {
return null;
}
List<CompanyBean> mList = new ArrayList<>();
for (int i = 0; i < resultCounts; i++) {
CompanyBean company = new CompanyBean();
company.id = cursor.getInt(cursor.getColumnIndex(KEY_ID));
company.name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
company.ceo = cursor.getString(cursor.getColumnIndex(KEY_CEO));
company.year = cursor.getInt(cursor.getColumnIndex(KEY_YEAR));
mList.add(company);
cursor.moveToNext();
}
return mList;
}
}
在 db 文件夹下建立一个 DBMaster 用于管理数据库里的全部数据表
/**
* 数据库总操作类
* @author dlong
* created at 2019/3/13 11:29 AM
*/
public class DBMaster {
/** 上下文 */
private Context mContext;
private SQLiteDatabase mDatabase;
private DBOpenHelper mDbOpenHelper;
/** 数据表操作类实例化 */
public PhoneDBDao mPhoneDBDao;
public CompanyDBDao mCompanyDBDao;
public DBMaster(Context context){
mContext = context;
mPhoneDBDao = new PhoneDBDao(mContext);
mCompanyDBDao = new CompanyDBDao(mContext);
}
/**
* 打开数据库
*/
public void openDataBase() {
mDbOpenHelper = new DBOpenHelper(mContext, DB_NAME, null, DB_VERSION);
try {
mDatabase = mDbOpenHelper.getWritableDatabase();//获取可写数据库
} catch (SQLException e) {
mDatabase = mDbOpenHelper.getReadableDatabase();//获取只读数据库
}
// 设置数据库的SQLiteDatabase
mPhoneDBDao.setDatabase(mDatabase);
mCompanyDBDao.setDatabase(mDatabase);
}
/**
* 关闭数据库
*/
public void closeDataBase() {
if (mDatabase != null) {
mDatabase.close();
}
}
/** 创建该数据库下phone表的语句 */
private static final String mPhoneSqlStr = "create table if not exists " + PhoneDBDao.TABLE_NAME + " (" +
PhoneDBDao.KEY_ID + " integer primary key autoincrement , " +
PhoneDBDao.KEY_BRAND + " text not null , " +
PhoneDBDao.KEY_MODEL + " text not null , " +
PhoneDBDao.KEY_PRICE + " integer );";
/** 创建该数据库下Company表的语句 */
private static final String mCompanySqlStr = "create table if not exists " + CompanyDBDao.TABLE_NAME + " (" +
CompanyDBDao.KEY_ID + " integer primary key autoincrement , " +
CompanyDBDao.KEY_NAME + " text not null , " +
CompanyDBDao.KEY_CEO + " text not null , " +
CompanyDBDao.KEY_YEAR + " integer );";
/** 删除该数据库下phone表的语句 */
private static final String mPhoneDelSql = "DROP TABLE IF EXISTS " + PhoneDBDao.TABLE_NAME;
/** 删除该数据库下Company表的语句 */
private static final String mCompanyDelSql = "DROP TABLE IF EXISTS " + CompanyDBDao.TABLE_NAME;
/**
* 数据表打开帮助类
*/
public static class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mPhoneSqlStr);
db.execSQL(mCompanySqlStr);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(mPhoneDelSql);
db.execSQL(mCompanyDelSql);
onCreate(db);
}
}
}
在 app 文件夹建立 MyApplication
public class MyApplication extends Application {
/** 声明数据库操作实例 */
public static DBMaster mDBMaster;
@Override
public void onCreate() {
super.onCreate();
//启动数据库
mDBMaster = new DBMaster(getApplicationContext());
mDBMaster.openDataBase();
}
}
还要在 AndroidManifest.xml 的 demo:MultipleDataSheetTestandroid:name=".app.MyApplication"
五、使用
// 新实例化一个PHONE
PhoneBean phone = new PhoneBean();
phone.brand = "Google";
phone.model = "Pixel 3";
phone.price = 4999;
// 插入数据库
MyApplication.mDBMaster.mPhoneDBDao.insertData(phone);
// 删除最老的一个数据
if (null != mPhoneList && mPhoneList.size()>0){
MyApplication.mDBMaster.mPhoneDBDao.deleteData(mPhoneList.get(0).id);
updatePhoneTxt();
}
// 查询数据库里的所有数据
mPhoneList = MyApplication.mDBMaster.mPhoneDBDao.queryDataList();
// 数据为空,也不能让列表为null
if (null == mPhoneList) mPhoneList = new ArrayList<>();
GitHub