android 一個SQLite數據庫多個數據表(帶demo)
前言
demo演示
1、搭建
2、創建實體類
3、創建數據庫操做類
4、配置Application
5、使用
GitHub
前言
個人上一篇博客講的是簡單的 android SQLite 數據庫的基本操做如增刪改查,有興趣的朋友能夠點一下這裏android 簡單SQLite數據庫 增刪改查
可是呢,通常的項目裏,一個數據庫也不會只有一個數據表,經常是多個數據表共同管理的,這個時候應該怎麼搭建項目的數據庫操做代碼框架呢?
光說不練假把式,動手開一個Demo
demo演示
demo
1、搭建
首先,在項目裏創建起三個文件夾,分別是 app 、 db 、 model
文件夾
app 文件夾下存放繼承 Application 的 MyApplication 類
db 文件夾下存放 數據庫操做類
model 文件夾下存放 數據實體類
2、創建實體類
在 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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
在 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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
3、創建數據庫操做類
在 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;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
在 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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
在 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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
在 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);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
4、配置Application
在 app 文件夾創建 MyApplication
public class MyApplication extends Application {
/** 聲明數據庫操做實例 */
public static DBMaster mDBMaster;
@Override
public void onCreate() {
super.onCreate();
//啓動數據庫
mDBMaster = new DBMaster(getApplicationContext());
mDBMaster.openDataBase();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
還要在 AndroidManifest.xml 的 <application 裏添加
android:name=".app.MyApplication"
1
5、使用
// 新實例化一個PHONE
PhoneBean phone = new PhoneBean();
phone.brand = "Google";
phone.model = "Pixel 3";
phone.price = 4999;
// 插入數據庫
MyApplication.mDBMaster.mPhoneDBDao.insertData(phone);
1
2
3
4
5
6
7
// 刪除最老的一個數據
if (null != mPhoneList && mPhoneList.size()>0){
MyApplication.mDBMaster.mPhoneDBDao.deleteData(mPhoneList.get(0).id);
updatePhoneTxt();
}
1
2
3
4
5
// 查詢數據庫裏的全部數據
mPhoneList = MyApplication.mDBMaster.mPhoneDBDao.queryDataList();
// 數據爲空,也不能讓列表爲null
if (null == mPhoneList) mPhoneList = new ArrayList<>();
---------------------
做者:YD-10-NG
來源:CSDN
原文:https://blog.csdn.net/sinat_38184748/article/details/88532631
版權聲明:本文爲博主原創文章,轉載請附上博文連接!android