最近學習安卓遇到了對數據庫的操作,用到了SQLiteOpenHelper這個類來連接或者創建數據庫,通過getWritableDatabase()或者getReadableDatabase(),來對錶進行寫入或讀取操作。
1. 爲什麼需要SQLiteOpenHelper?
SQLiteOpenHelper重點在於helper,他是SQLiteDatabase的一個幫助類,便於開發者實現對SQLite的數據進行寫入(增刪改)和讀取(查詢)。
2. SQLiteOpenHelper具體有什麼方法?
使用SQLiteOpenHelper,便是構建一個類將其繼承,有三個方法必須實現:
2.1 構造方法
SQLiteOpenHelper有許多構造方法,最常用的是這種:
public SQLiteOpenHelper(@Nullable Context context,
@Nullable String name,
@Nullable CursorFactory factory,
int version)
{
this(context, name, factory, version, null);
}
可以看見有四個參數,分別是:
- 上下文
- 數據庫名稱
- 遊標工廠
- 版本號
而其代碼塊部分調的是另一個構造函數,最後一個參數爲null,不需考慮。
2.2 oncreate()方法
由於是抽象方法,所以子類一定要實現;
它的作用是數據庫第一次創建時,進入執行;一般將創建表的sql語句寫進其中。
一個參數:當前連接或者創建的SQLiteDatabase對象
//數據庫第一次創建時調用的函數
public abstract void onCreate(SQLiteDatabase db);
2.3 onUpgrade()方法
它的作用是數據庫的版本號更新(增加時),進入執行;一般將修改表整體結構的sql語句寫入其中。
三個參數:當前連接或者創建的SQLiteDatabase對象、舊版本號、新版本號
//數據庫版本版本號增加時調用的函數
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
3. 如何使用SQLiteOpenHelper(具體實例)?
3.1 數據連接層 MySQLiteHelper(名字自擬)
定義一個類繼承SQLiteOpenHelper
我這裏類名叫MySQLiteHelper,屬性:數據庫名demo、表名user、版本1。
注意:子類的構造函數可以只傳一個上下文,其餘直接賦屬性值,因爲基本不會變化(特殊情況除外)
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME= "demo";//數據庫名稱
private final static String TABLE_NAME= "user";//表名
private final static int VERSION= 1;//當前版本
//參數分別是:上下文,數據庫名,遊標工廠,數據庫版本
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
//數據庫第一次創建時調用的函數
@Override
public void onCreate(SQLiteDatabase db) {
String sql="Create table "+
TABLE_NAME+
"(" +
"id integer primary key autoincrement," +
"username varchar(20)," +
"password varchar(20)" +
")";
db.execSQL(sql);
}
//數據庫版本版本號增加時調用的函數
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("hc", "onUpgrade: 版本更新了!");
}
}
3.2 數據訪問層 MySQLiteDao(名字自擬)
這個類就把所有對數據表的操作封裝,每一個操作寫一個方法:增、刪、改、查、清空
將這個類的構造函數作爲MySQLiteHelper連接類的實現方法
通過logcat的hc標籤來查看結果
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteDao {
private MySQLiteHelper mySQLiteHelper;
//構造函數,實例化MySQLiteHelper
public MySQLiteDao(Context context){
this.mySQLiteHelper=new MySQLiteHelper(context);
Log.d("hc", "MySQLiteDao: 創建或連接");
}
//簡單的固定增加
public void add(){
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
String sql="insert into user values(null,?,?)";
db.execSQL(sql,new String[]{"小明","123"});
//關閉db通道
db.close();
Log.d("hc", "add: 新增");
}
//簡單的全查
public List<User> queryAll(){
SQLiteDatabase db = mySQLiteHelper.getReadableDatabase();
List<User> users= new ArrayList<>();//user集合
User user=null;//單個user
String sql="select * from user";
Cursor cursor=db.rawQuery(sql,null);
while (cursor.moveToNext()){
//單個user賦值
user=new User(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2)
);
//放到集合中
users.add(user);
}
//關閉db通道
db.close();
Log.d("hc", "queryAll: 全查");
return users;
}
//簡單的通過id來修改,值已寫死
public void update(int id){
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
String sql="update user set username=?,password=? where id=?";
db.execSQL(sql,new String[]{"小紅","10086",String.valueOf(id)});
//關閉db通道
db.close();
Log.d("hc", "update: 修改");
}
//簡單的通過id來刪除
public void delete(int id){
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
String sql="delete from user where id= ?";
db.execSQL(sql,new String[]{String.valueOf(id)});
//關閉db通道
db.close();
Log.d("hc", "delete: 刪除");
}
//簡單的刪除,清空數據庫數據
public void deleteAll(){
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
String sql="delete from user";
db.execSQL(sql);
//關閉db通道
db.close();
Log.d("hc", "deleteAll: 清空");
}
}
3.3 數據控制層 MainActivity(自擬,不過這個是原生的)
作爲實現與手機交互的activity,它需要對事件進行處理,我這裏只有點擊事件,實現自身類監聽點擊事件,根據id值判斷點擊的哪個按鈕,刪除和修改根據輸入框的id數值來執行具體操作。
注意:如果android studio版本過低,繼承的AppCompatActivity無法找到,請繼承Activity
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCreate;
private Button btnInsert;
private Button btnQuery;
private Button btnUpdate;
private Button btnDelete;
private Button btnDeleteAll;
private EditText et;
private MySQLiteDao mySQLiteDao;//數據訪問層,包含數據庫的啓動
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//初始化
private void init(){
btnCreate=findViewById(R.id.create);
btnInsert=findViewById(R.id.insert);
btnQuery=findViewById(R.id.query);
btnUpdate=findViewById(R.id.update);
btnDelete=findViewById(R.id.delete);
btnDeleteAll=findViewById(R.id.deleteAll);
et=findViewById(R.id.et);
btnCreate.setOnClickListener(this);
btnInsert.setOnClickListener(this);
btnQuery.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnDeleteAll.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.create:
mySQLiteDao=new MySQLiteDao(this);
break;
case R.id.insert:
mySQLiteDao.add();
break;
case R.id.query://全查後從logcat輸出
List<User> users=mySQLiteDao.queryAll();
if (users.isEmpty()){
Log.d("hc", "沒有數據哦!");
}
for (User user:users){
Log.d("hc",
"id: "+user.getId()+
"\tusername: "+user.getUsername()+
"\tpassword: "+user.getPassword());
}
break;
case R.id.update:
//拿到需要需改的id
if (et.length()==0){//沒有就彈出提示
Toast.makeText(this,"id值沒填",Toast.LENGTH_SHORT).show();
Log.d("hc", "請輸入需要修改的id");
}else {//有就去修改
mySQLiteDao.update(Integer.valueOf(et.getText().toString()));
}
break;
case R.id.delete:
//拿到需要刪除的id
if (et.length()==0){//沒有就彈出提示
Toast.makeText(this,"id值沒填",Toast.LENGTH_SHORT).show();
Log.d("hc", "請輸入需要刪除的id");
}else {//有就去刪除
mySQLiteDao.delete(Integer.valueOf(et.getText().toString()));
}
break;
case R.id.deleteAll:
mySQLiteDao.deleteAll();
break;
}
}
}
3.4 User實體類(自擬,跟數據庫的表名一致最好)
這個實體類的屬性需跟數據表的列名一致,便於操作與記憶
//user實體類
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
3.5 activity的佈局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:text="數據庫簡單小框架"
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:gravity="center"
android:layout_marginTop="10dp"/>
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入修改和刪除的id值"
android:layout_marginTop="20dp"/>
<Button
android:text="創建或連接數據庫"
android:id="@+id/create"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"/>
<Button
android:text="插入數據"
android:id="@+id/insert"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="查詢數據"
android:id="@+id/query"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text=" 修改指定數據"
android:id="@+id/update"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text=" 刪除指定數據"
android:id="@+id/delete"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="清空數據"
android:id="@+id/deleteAll"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
3.6 實現結果(注意,一定要先點連接數據庫纔可以進行其他操作)
手機
logcat查看hc
好,SQLiteOpenHelper簡單實現增刪改查的全部內容到此爲止。
如果有收穫的小夥伴投個幣點個贊吧,謝謝~