新聞中心
安卓開發(fā)中,SQLite是一種常用的數(shù)據(jù)庫存儲(chǔ)方式。SQLite是一種輕量級(jí)的嵌入式關(guān)系型數(shù)據(jù)庫管理系統(tǒng),它在安卓平臺(tái)中可以快速、高效的進(jìn)行數(shù)據(jù)的存儲(chǔ)和管理,因此,在安卓應(yīng)用開發(fā)中使用SQLite也成為了一種非常普遍的方式。

成都創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括豐寧網(wǎng)站建設(shè)、豐寧網(wǎng)站制作、豐寧網(wǎng)頁制作以及豐寧網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,豐寧網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到豐寧省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
本文將介紹如何訪問SQLite數(shù)據(jù)庫,讓你快速掌握在安卓開發(fā)中使用SQLite的技能。
一、安卓中SQLite數(shù)據(jù)庫的使用
SQLite是一種輕量級(jí)的嵌入式數(shù)據(jù)庫,在安卓中使用SQLite非常方便。需要注意的是,由于安卓應(yīng)用開發(fā)通常是基于Java語言進(jìn)行的,而SQLite是由C語言編寫的,因此,需要使用Java語言中的一些特定的API接口來訪問SQLite數(shù)據(jù)庫。
1.1 安卓中SQLite數(shù)據(jù)庫的API
在安卓中,可以使用以下API來訪問SQLite數(shù)據(jù)庫:
(1)android.database.sqlite.SQLiteDatabase類:該類提供了訪問SQLite數(shù)據(jù)庫的方法,包括查詢、更新、插入和刪除數(shù)據(jù)等基本操作。
(2)android.database.sqlite.SQLiteOpenHelper類:該類用于幫助創(chuàng)建和管理SQLite數(shù)據(jù)庫??梢允褂迷擃悂韯?chuàng)建和打開SQLite數(shù)據(jù)庫,以及升級(jí)該數(shù)據(jù)庫的版本。
1.2 在Android Studio中創(chuàng)建SQLite數(shù)據(jù)庫
Android Studio是連接安卓開發(fā)和SQLite數(shù)據(jù)庫的更佳工具。需要注意的是,在Android Studio中,我們可以通過三種方式來創(chuàng)建SQLite數(shù)據(jù)庫:
1.2.1 基于SQLiteOpenHelper創(chuàng)建
SQLiteOpenHelper是Android提供的簡化SQLite數(shù)據(jù)庫使用的一個(gè)幫助類。我們可以繼承SQLiteOpenHelper,在子類中重寫onCreate()方法和onUpgrade()方法,來處理數(shù)據(jù)庫的創(chuàng)建和升級(jí)操作。具體的操作如下:
(1)創(chuàng)建一個(gè)新的Java類,并繼承SQLiteOpenHelper類。
(2)在子類中重寫onCreate()方法,該方法用于在數(shù)據(jù)庫之一次創(chuàng)建時(shí)執(zhí)行,負(fù)責(zé)創(chuàng)建數(shù)據(jù)庫的表和存儲(chǔ)過程等。
(3)在子類中重寫onUpgrade()方法,該方法用于在數(shù)據(jù)庫版本升級(jí)時(shí)執(zhí)行,通過該方法可以刪除原有的數(shù)據(jù)表,并創(chuàng)建新的數(shù)據(jù)表以及存儲(chǔ)過程等。
(4)在應(yīng)用程序中實(shí)例化該類,并使用getReadableDatabase()方法或者getWritableDatabase()方法來獲取一個(gè)用于訪問數(shù)據(jù)庫的SQLiteDatabase對(duì)象。
示例代碼:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = “create table Book (“
+ “id integer primary key autoincrement, “
+ “author text, “
+ “price float, “
+ “pages integer, “
+ “name text)”;
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext, “Create succeeded”, Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(“drop table if exists Book”);
onCreate(db);
}
}
1.2.2 基于SQLite語句創(chuàng)建
使用Android Studio的SqliteDatabase類,我們可以通過執(zhí)行SQL語句來創(chuàng)建SQLite數(shù)據(jù)庫和數(shù)據(jù)表,示例代碼如下:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = “test.db”;
private static final String TABLE_NAME = “users”;
private static final String COLUMN_ID = “id”;
private static final String COLUMN_NAME = “name”;
private static final String COLUMN_EML = “eml”;
private static final String COLUMN_PASSWORD = “password”;
private static final String CREATE_USERS_QUERY = “CREATE TABLE “+TABLE_NAME +” (“+
COLUMN_ID +” INTEGER PRIMARY KEY AUTOINCREMENT,”+
COLUMN_NAME+” TEXT,”+
COLUMN_EML+” TEXT,”+
COLUMN_PASSWORD+” TEXT)”;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_USERS_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase database, int i, int i1) {
database.execSQL(“DROP TABLE IF EXISTS “+TABLE_NAME );
onCreate(database);
}
}
1.2.3 使用ORM創(chuàng)建
ORM(Object-Relational Mapping)是一種將對(duì)象模型與關(guān)系型數(shù)據(jù)庫模型進(jìn)行映射的技術(shù)。在Android Studio中,可以使用ORM庫來簡化SQLite數(shù)據(jù)庫的操作。一些常見的ORM庫有:GreenDAO和OrmLite等。這里以GreenDAO為例,來介紹如何使用ORM來創(chuàng)建SQLite數(shù)據(jù)庫:
(1)在build.gradle文件中添加GreenDAO的依賴:
dependencies {
implementation ‘org.greenrobot:greendao:3.2.2’
}
(2)在Java文件中,定義數(shù)據(jù)模型和數(shù)據(jù)操作類:
@Entity
public class User {
@Id(autoincrement = true)
private Long id;
private String name;
private String eml;
private String password;
// getter和setter方法
}
public class UserDao {
private final DaoSession daoSession;
private final UserDao userDao;
public UserDao(DaoSession daoSession) {
this.daoSession = daoSession;
userDao = daoSession.getUserDao();
}
public void insertUser(User user) {
userDao.insert(user);
}
public void deleteUser(User user) {
userDao.delete(user);
}
public User findUserById(Long id) {
return userDao.load(id);
}
public List getAllUsers() {
return userDao.loadAll();
}
}
(3)在Application中初始化GreenDAO:
public class App extends Application {
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
@Override
public void onCreate() {
super.onCreate();
setDatabase();
}
private void setDatabase(){
mHelper = new DaoMaster.DevOpenHelper(this, “mydb”, null);
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public DaoMaster getDaoMaster() {
return mDaoMaster;
}
public SQLiteDatabase getDb() {
return db;
}
}
二、安卓中SQLite數(shù)據(jù)庫的操作
在Android Studio中創(chuàng)建和連接SQLite數(shù)據(jù)庫以后,我們可以使用以下幾種方式來訪問數(shù)據(jù)庫:
2.1 插入數(shù)據(jù)
使用SQLiteDatabase類的insert()方法,可以向數(shù)據(jù)表中添加數(shù)據(jù),例如:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“name”, “The Da Vinci Code”);
values.put(“author”, “Dan Brown”);
values.put(“pages”, 454);
values.put(“price”, 16.96);
db.insert(“Book”, null, values);
2.2 更新數(shù)據(jù)
使用SQLiteDatabase類的update()方法,可以更新數(shù)據(jù)表中的數(shù)據(jù),例如:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“price”, 10.99);
db.update(“Book”, values, “name = ?”, new String[] { “The Da Vinci Code” });
2.3 查詢數(shù)據(jù)
使用SQLiteDatabase類的query()方法,可以查詢數(shù)據(jù)表中的數(shù)據(jù),例如:
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(“Book”, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(“name”));
String author = cursor.getString(cursor.getColumnIndex(“author”));
int pages = cursor.getInt(cursor.getColumnIndex(“pages”));
double price = cursor.getDouble(cursor.getColumnIndex(“price”));
} while (cursor.moveToNext());
}
cursor.close();
2.4 刪除數(shù)據(jù)
使用SQLiteDatabase類的delete()方法,可以從數(shù)據(jù)表中刪除數(shù)據(jù),例如:
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(“Book”, “pages > ?”, new String[] { “500” });
三、安卓SQLite數(shù)據(jù)庫的一個(gè)使用案例
下面是一個(gè)簡單的案例,說明如何使用安卓中的SQLite數(shù)據(jù)庫實(shí)現(xiàn)簡單的數(shù)據(jù)存儲(chǔ)。
該案例的功能:實(shí)現(xiàn)簡單的分類記賬,記錄用戶的收入、支出及余額情況,并在圖表中顯示出這些數(shù)據(jù)。
3.1 創(chuàng)建數(shù)據(jù)庫和表結(jié)構(gòu)
我們需要?jiǎng)?chuàng)建兩個(gè)表來表示流水賬單記錄和賬單分類,具體的SQL代碼如下:
CREATE TABLE t_bill_category (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL
);
CREATE TABLE t_record_income (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
amount REAL NOT NULL,
time INTEGER NOT NULL,
category_id INTEGER NOT NULL,
FOREIGN KEY (category_id) REFERENCES t_bill_category (id)
);
CREATE TABLE t_record_expense (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
amount REAL NOT NULL,
time INTEGER NOT NULL,
category_id INTEGER NOT NULL,
FOREIGN KEY (category_id) REFERENCES t_bill_category (id)
);
3.2 創(chuàng)建Java類
我們需要?jiǎng)?chuàng)建三個(gè)Java類來實(shí)現(xiàn)相關(guān)功能:一個(gè)是AccountingDatabaseHelper類,用于創(chuàng)建和維護(hù)SQLite數(shù)據(jù)庫;一個(gè)是Category類,用于表示賬單類別;一個(gè)是Record類,用于表示收支流水記錄。
AccountingDatabaseHelper類代碼:
public class AccountingDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = “accounting.db”;
public static final int DATABASE_VERSION = 1;
private static final String CREATE_CATEGORY_TABLE_SQL = “CREATE TABLE IF NOT EXISTS t_bill_category (” +
“id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,” +
“name TEXT NOT NULL,” +
“type TEXT NOT NULL);”;
private static final String CREATE_INCOME_RECORD_TABLE_SQL = “CREATE TABLE IF NOT EXISTS t_record_income (” +
“id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,” +
“amount REAL NOT NULL,” +
“time INTEGER NOT NULL,” +
“category_id INTEGER NOT NULL,” +
“FOREIGN KEY (category_id) REFERENCES t_bill_category (id));”;
private static final String CREATE_EXPENSE_RECORD_TABLE_SQL = “CREATE TABLE IF NOT EXISTS t_record_expense (” +
“id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,” +
“amount REAL NOT NULL,” +
“time INTEGER NOT NULL,” +
“category_id INTEGER NOT NULL,” +
“FOREIGN KEY (category_id) REFERENCES t_bill_category (id));”;
private static final String[] INSERT_CATEGORY_DATA_SQL =
{“INSERT INTO t_bill_category (id,name,type) values (1,’餐飲’,’EXPENSE’)”,
“INSERT INTO t_bill_category (id,name,type) values (2,’交通’,’EXPENSE’)”,
“INSERT INTO t_bill_category (id,name,type) values (3,’工資’,’INCOME’)”,
“INSERT INTO t_bill_category (id,name,type) values (4,’津貼’,’INCOME’)”};
AccountingDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CATEGORY_TABLE_SQL);
db.execSQL(CREATE_INCOME_RECORD_TABLE_SQL);
db.execSQL(CREATE_EXPENSE_RECORD_TABLE_SQL);
for (String sql : INSERT_CATEGORY_DATA_SQL) {
db.execSQL(sql);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Category類代碼:
@Entity
public class Category {
@Id(autoincrement = true)
private Long id;
private String name;
private String type;
public Category() {
}
public Category(String name, String type) {
this.name = name;
this.type = type;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Record類代碼:
public class Record {
private Long id;
private double amount;
private long time;
private Category category;
public Record(double amount, long time, Category category) {
this.amount = amount;
this.time = time;
this.category = category;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
3.3 實(shí)現(xiàn)插入、查詢和刪除功能
在主Activity中,定義以下方法來實(shí)現(xiàn)插入、查詢和刪除等操作:
public Long saveRecord(Record record) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“amount”, record.getAmount());
values.put(“time”, record.getTime());
values.put(“category_id”, record.getCategory().getId());
long id = db.insert(record.getCategory().getType().equalsIgnoreCase(“INCOME”) ? “t_record_income” : “t_record_expense”, null, values);
db.close();
return id;
}
public void deleteRecord(long id,String categoryType) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(categoryType.equalsIgnoreCase(“INCOME”) ? “t_record_income” : “t_record_expense”, “id=?”, new String[]{String.valueOf(id)});
db.close();
}
public List getAllRecords(String categoryType) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(categoryType.equalsIgnoreCase(“INCOME”) ? “t_record_income” : “t_record_expense”, null, null, null, null, null, “time DESC”);
ArrayList records = new ArrayList();
while (cursor.moveToNext()) {
Long id = cursor.getLong(cursor.getColumnIndex(“id”));
double amount = cursor.getDouble(cursor.getColumnIndex(“amount”));
long time = cursor.getLong(cursor.getColumnIndex(“time”));
Long categoryId = cursor.getLong(cursor.getColumnIndex(“category_id”));
Category category = null;
Cursor categoryCursor = db.query(“t_bill_category”, null, “id=?”, new String[]{String.valueOf(categoryId)}, null, null, null);
if (categoryCursor.moveToFirst()) {
String categoryName = categoryCursor.getString(categoryCursor.getColumnIndex(“name”));
String categoryDbType = categoryCursor.getString(categoryCursor.getColumnIndex(“type”));
category = new Category(categoryName, categoryDbType);
category.setId(categoryId);
}
Record record = new Record(amount, time, category);
record.setId(id);
records.add(record);
categoryCursor.close();
}
cursor.close();
db.close();
return records;
}
3.4 實(shí)現(xiàn)圖表功能
我們通過使用MPAndroidChart庫來實(shí)現(xiàn)將收支記錄數(shù)據(jù)在圖表中展示的功能,總代碼參考如下:
public class MnActivity extends AppCompatActivity {
private LinearLayout mLayoutExpense;
private LinearLayout mLayoutIncome;
private TextView mTextTotalExpense;
private TextView mTextTotalIncome;
private TextView mTextTotal;
private LineChart mChart;
private AccountingDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mn);
// 初始化UI組件
initView();
dbHelper = new AccountingDatabaseHelper(this);
// 初始化數(shù)據(jù)
initData();
// 初始化圖表
initChart();
}
private void initView() {
mLayoutExpense = findViewById(R.id.ll_expense);
mLayoutIncome = findViewById(R.id.ll_income);
mTextTotalExpense = findViewById(R.id.tv_total_expense);
mTextTotalIncome = findViewById(R.id.tv_total_income);
mTextTotal = findViewById(R.id.tv_total);
mChart = findViewById(R.id.chart);
}
private void initData() {
double totalExpense = 0;
double totalIncome = 0;
// TODO: 從數(shù)據(jù)庫中查詢多個(gè)月份的收支記錄數(shù)據(jù)
List expenseRecords = getAllRecords(“EXPENSE”);
for (int i = 0; i
Record record = expenseRecords.get(i);
addRecordView(record, mLayoutExpense);
totalExpense += record.getAmount();
}
List incomeRecords = getAllRecords(“INCOME”);
for (int i = 0; i
Record record = incomeRecords.get(i);
addRecordView(record, mLayoutIncome);
totalIncome += record.getAmount();
}
mTextTotalExpense.setText(String.format(Locale.getDefault(), “%.2f”, totalExpense));
mTextTotalIncome.setText(String.format(Locale.getDefault(), “%.2f”, totalIncome));
mTextTotal.setText(String.format(Locale.getDefault(), “%.2f”, totalIncome – totalExpense));
}
private void addRecordView(Record record, LinearLayout layout) {
View recordView = LayoutInflater.from(this).inflate(R.layout.layout_record_item, null);
TextView textView1 = recordView.findViewById(R.id.tv_item_name);
TextView textView2 = recordView.findViewById(R.id.tv_item_amount);
textView1.setText(record.getCategory().getName());
textView2.setText(String.format(Locale.getDefault(), “%.2f”, record.getAmount()));
layout.addView(recordView);
}
private void initChart() {
相關(guān)問題拓展閱讀:
- android怎么連接sqlite數(shù)據(jù)庫?
android怎么連接sqlite數(shù)據(jù)庫?
android 集行純成了sqlite數(shù)據(jù)庫
用法很簡單的,這里說不清楚辯粗,看攜帶鎮(zhèn)看視頻教程吧
這里說的很詳細(xì)
關(guān)于安卓 訪問sqlite數(shù)據(jù)庫的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關(guān)注本站。
香港服務(wù)器選創(chuàng)新互聯(lián),2H2G首月10元開通。
創(chuàng)新互聯(lián)(www.cdcxhl.com)互聯(lián)網(wǎng)服務(wù)提供商,擁有超過10年的服務(wù)器租用、服務(wù)器托管、云服務(wù)器、虛擬主機(jī)、網(wǎng)站系統(tǒng)開發(fā)經(jīng)驗(yàn)。專業(yè)提供云主機(jī)、虛擬主機(jī)、域名注冊(cè)、VPS主機(jī)、云服務(wù)器、香港云服務(wù)器、免備案服務(wù)器等。
當(dāng)前文章:安卓應(yīng)用開發(fā):如何訪問SQLite數(shù)據(jù)庫?(安卓訪問sqlite數(shù)據(jù)庫)
當(dāng)前URL:http://fisionsoft.com.cn/article/cdccjii.html


咨詢
建站咨詢
