目錄
一、初識Android資料庫
二、表中資料的添加操作
三、資料表中資料的洗掉
1、洗掉全部資料
2、單條資料的洗掉
四、資料表中單條資料指定值的修改
五、資料表中資料的查找
1、查找全部資料
2、查詢單條資料
六、完整專案案例原始碼
Hello,你好呀,我是灰小猿!一個超會寫bug的程式猿!
最近和大家分享了很多關于Python開發的相關文章,今天就換個口味,在這里和大家記錄一下在Android開發中連接資料庫并進行基本操作的相關內容,
Android中的資料庫使用和其他語言中的資料庫使用基本相似,都是基于mysql中最基本的操作陳述句進行的,我們都知道,不論是哪種語言的應用開發,到之后都是要依托于強大的資料處理的,所以對于基本資料庫的操作開發的熟練掌握也是非常重要的,接下來,我就和大家總結學習一下在Android中進行資料庫開發的基本操作,感興趣的小伙伴可以關注一起學習呀!

我們全文以創建“school”資料庫和“student”資料表為例,資料表中的屬性是:“name”表示姓名、“class”表示班級,并對表中資料進行基本的增、刪、改、查和清空操作,來對資料庫的基本操作進行實體化講解!
一、初識Android資料庫
在Android的資料庫開發中,使用的基礎資料庫是用SQLiteDatabase創建的,它和基本的MySQL資料庫在操作上基本相同,但是同時也植入了Android開發中一些特有的屬性,在MainActivity.java檔案中,資料庫的創建陳述句是:
SQLiteDatabase db = openOrCreateDatabase("school", Context.MODE_PRIVATE,null);
上述這句話的意思是:打開或創建資料庫,也就是說,如果該資料庫已經存在,那么就將其打開,如果不存在,那么就創建它,其中的三個引數分別是:資料庫名稱、資料庫檔案的操作模式、回傳值(一般為null),
關于資料庫檔案的操作模式,可以有以下這幾個引數:
- Context.MODE_PRIVATE:為默認操作模式,代表該檔案是私有資料,只能被應用本身訪問,在該模式下,寫入的內容會覆寫原檔案的內容,如果想把新寫入的內容追加到原檔案中,可以使用Context.MODE_APPEND
- Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就創建新檔案,
- Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有權限讀寫該檔案,
- MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取;
- MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入,
現在創建好資料庫之后,就是進行資料表的創建,資料表的創建我們可以在execSQL()函式中寫入,該函式的引數就是一條標準的sql陳述句,作用就是執行其中的sql陳述句,以下代碼中sql陳述句的作用是如果student資料表不存在,就創建student資料表,
db.execSQL("create table if not exists student(name varchar(10),class varchar(10))");
其中我們創建的資料庫可以在以下檔案夾中找到,

在data檔案夾下知道資料庫檔案存放的路徑

至此,基本的資料庫和資料表已經創建完成了,接下來利用實體來和大家分享在資料表中進行資料的增、刪、改、查操作,
二、表中資料的添加操作
在資料表中增加資料與平常在資料庫中增加資料稍有不同,在這里需要用到一個存盤類ContentValues,該類和HashTable類似都是一種存盤的機制,但是兩者最大的區別就在于,contenvalues只能存盤基本型別的資料,像string,int之類的,不能存盤物件,而HashTable卻可以存盤物件,ContentValues存盤物件的時候,以(key,value)的形式來存盤資料,
在Android的資料庫中插入資料時,首先應該創建一個ContentValues類物件,呼叫該類的put()方法來輸入資料,之后使用資料庫的insert()方法直接將插入了資料的ContentValues物件傳進去即可,
具體操作可以看下面的實體:
//增加資料
public void add(){
ContentValues cv = new ContentValues();
cv.put("name","張三");
cv.put("class","軟體工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","李四");
cv.put("class","網路工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","王五");
cv.put("class","物聯網工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","趙六");
cv.put("class","計算機科學");
db.insert("student",null,cv);
}
其中涉及到了一個ContentValues類的clear()方法,
在這里要注意一點:當我們在需要插入多條資料的時候,顯然創建一個ContentValues類物件是不可以的,因為在key值相同的情況下,它只能接收一個value值,那么怎么辦?所以這里就用到了clear()方法,該方法的作用是清除ContentValues類物件中存盤的資料,也就是說當你第二次呼叫該物件并向其中插入資料的時候,該物件內是空的,同時要注意,每次插入一條資料之后,都需要使用insert()方法將其寫入資料表中,
三、資料表中資料的洗掉
1、洗掉全部資料
我們在上邊提到了一個關于sql的函式execSQL()函式,同時也介紹了該函式主要是用來執行sql陳述句的,那么我們在進行資料表中資料的洗掉時,就可以使用該函式方法,首先來看洗掉資料表中的全部資料:
db.execSQL("delete from student");
以上代碼即可將“student”資料表中的所有資料洗掉,
2、單條資料的洗掉
和洗掉全部資料的方法一樣,我們在進行資料表中單條資料的洗掉時,同樣是使用execSQL()函式,唯一不同的就是在sql陳述句后面增加一個限定條件,限定洗掉的內容,操作陳述句如下:如我們要洗掉姓名為“李四”的學生資訊,
db.execSQL("delete from student where name=?",new String[]{"李四"});
觀察上述代碼,可以發現,在指定洗掉姓名的時候,后面帶了一個引數,同時該引數是寫在string陣列之中的,這一點需要注意:也就是說當我們有多個限定條件的時候,也就是sql陳述句中有多個問號的時候,字符陣列中存放的資料應該按照問號的次序依次寫入陣列,接下來我們就以值的修改來驗證,
四、資料表中單條資料指定值的修改
資料值的修改操作同樣是在execSQL()函式中執行的,我們以將(“王五”:“物聯網工程”)修改為(“王五”:“自動化”)為例,sql陳述句中需要傳入兩個值:
db.execSQL("update student set class=? where name=?",new String[]{"自動化","王五"});
上面的代碼可以看出,修改姓名為“王五”的同學的專業為“自動化”,字符陣列中帶有了兩個引數,
五、資料表中資料的查找
1、查找全部資料
由于資料的查找是需要回傳查找到的資料資訊的,所以資料的查找操作不能使用execSQL()函式來執行了,
這里我們需要使用一個專門用于進行資料查找,并且回傳其查找結果的函式rawQuery()函式,該函式的回傳值是一個游標型別的cursor,該游標會接收并存盤所有查詢到的結果,我們在讀取結果時需要依次移動游標的位置,來獲取每一個結果引數,我們以查詢資料表中所有資料為例,之后將查詢到的結果按行顯示在文本框中,
//查詢全部資料
private void query() {
Cursor cursor = db.rawQuery("select * from student",null);
int sum = cursor.getCount();
String queryInfo = "查詢到" + sum + "條記錄:\n";
for (int i=0;i<sum;i++){
cursor.moveToPosition(i);
String name = cursor.getString(0);
String classname = cursor.getString(1);
String info = name + " " + classname + "\n";
queryInfo += info;
}
textinfo.setText(queryInfo);
cursor.close();//關閉游標
}
2、查詢單條資料
查詢單條資料和查詢所有資料使用的函式和方法是一樣的,唯一不一樣的地方就是在查詢單條資料的時候是需要設定限定條件的,也就是在rawQuery()方法的sql陳述句后面增加一個限定引數,方法同樣是使用string陣列的形式,我們以查找姓名為“趙六”的學生資訊為例:
//查找單條資料
private void query_one() {
Cursor cursor = db.rawQuery("select * from student where name=?",new String[]{"趙六"});
int sum = cursor.getCount();//獲取到查詢的結果個數
String queryInfos = "查詢到" + sum + "條記錄:\n";
//回圈遍歷查詢結果,將值依次取出
for (int i = 0;i<sum;i++){
cursor.moveToPosition(i);//將游標移動到i的位置
String name = cursor.getString(0); //獲取到一個string資料
String classname = cursor.getString(1); //獲取到二個string資料
String info = name + " " + classname + "\n";
queryInfos += info;
}
textinfo.setText(queryInfos); //將資料加載到文本框顯示
cursor.close(); //關閉游標
}
六、完整專案案例原始碼
關于Android資料庫的增刪改查操作就講到這里,下面附上完整的專案原始碼和實作效果,能夠實作簡單的資料增刪改查及清空操作,:
Activity_main.xml檔案原始碼:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/add_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加"
android:textSize="30dp"
app:layout_constraintTop_toTopOf="parent"
></Button>
<Button
android:id="@+id/delete_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="洗掉"
android:textSize="30dp"
app:layout_constraintTop_toBottomOf="@id/add_bt"
></Button>
<Button
android:id="@+id/update_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="修改"
android:textSize="30dp"
app:layout_constraintTop_toBottomOf="@id/delete_bt"
></Button>
<Button
android:id="@+id/query_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查詢全部"
android:textSize="30dp"
app:layout_constraintTop_toBottomOf="@id/update_bt"
></Button>
<Button
android:id="@+id/queryOne_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查詢一條"
android:textSize="30dp"
app:layout_constraintTop_toBottomOf="@id/query_bt"
></Button>
<Button
android:id="@+id/deldelAll_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="清空資料庫"
android:textSize="30dp"
app:layout_constraintTop_toBottomOf="@id/queryOne_bt"
></Button>
<TextView
android:id="@+id/textinfo"
android:layout_width="match_parent"
android:layout_height="400dp"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="@id/deldelAll_bt"
></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java檔案原始碼:
package com.example.sqltest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button add_bt,delete_bt,update_bt,query_bt,queryOne_bt,delAll_bt;
TextView textinfo;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add_bt = findViewById(R.id.add_bt);
delete_bt = findViewById(R.id.delete_bt);
update_bt = findViewById(R.id.update_bt);
query_bt = findViewById(R.id.query_bt);
queryOne_bt = findViewById(R.id.queryOne_bt);
delAll_bt = findViewById(R.id.deldelAll_bt);
textinfo = findViewById(R.id.textinfo);
add_bt.setOnClickListener(this);
delete_bt.setOnClickListener(this);
update_bt.setOnClickListener(this);
query_bt.setOnClickListener(this);
queryOne_bt.setOnClickListener(this);
delAll_bt.setOnClickListener(this);
db = openOrCreateDatabase("school", Context.MODE_PRIVATE,null);
db.execSQL("create table if not exists student(name varchar(10),class varchar(10))");
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.add_bt:
add();
break;
case R.id.delete_bt:
delete();
break;
case R.id.update_bt:
update();
break;
case R.id.query_bt:
query();
break;
case R.id.queryOne_bt:
query_one();
break;
case R.id.deldelAll_bt:
delAll();
break;
}
}
//查找單條資料
private void query_one() {
Cursor cursor = db.rawQuery("select * from student where name=?",new String[]{"趙六"});
int sum = cursor.getCount();//獲取到查詢的結果個數
String queryInfos = "查詢到" + sum + "條記錄:\n";
//回圈遍歷查詢結果,將值依次取出
for (int i = 0;i<sum;i++){
cursor.moveToPosition(i);//將游標移動到i的位置
String name = cursor.getString(0); //獲取到一個string資料
String classname = cursor.getString(1); //獲取到二個string資料
String info = name + " " + classname + "\n";
queryInfos += info;
}
textinfo.setText(queryInfos); //將資料加載到文本框顯示
cursor.close(); //關閉游標
}
//洗掉全部資料
private void delAll() {
db.execSQL("delete from student");
}
//查詢全部資料
private void query() {
Cursor cursor = db.rawQuery("select * from student",null);
int sum = cursor.getCount();
String queryInfo = "查詢到" + sum + "條記錄:\n";
for (int i=0;i<sum;i++){
cursor.moveToPosition(i);
String name = cursor.getString(0);
String classname = cursor.getString(1);
String info = name + " " + classname + "\n";
queryInfo += info;
}
textinfo.setText(queryInfo);
cursor.close();//關閉游標
}
//修改單條資料
private void update() {
db.execSQL("update student set class=? where name=?",new String[]{"自動化","王五"});
}
//增加資料
public void add(){
ContentValues cv = new ContentValues();
cv.put("name","張三");
cv.put("class","軟體工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","李四");
cv.put("class","網路工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","王五");
cv.put("class","物聯網工程");
db.insert("student",null,cv);
cv.clear();
cv.put("name","趙六");
cv.put("class","計算機科學");
db.insert("student",null,cv);
}
//洗掉一條資料
private void delete() {
db.execSQL("delete from student where name=?",new String[]{"李四"});
}
}
運行效果:

關于Android資料庫的基本操作就和大家分享到這里,有問題的小伙伴可以在評論區留言提出,
之后還會繼續分享更多Android進階內容,
歡迎小伙伴們關注一起學習!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/282146.html
標籤:其他

