SQLite 資料庫存盤
寫在前面
SQLite 是一款輕量級的關系型資料庫,它的運算速度非常快,占用資源很少,通常只需要幾百K 的記憶體就足夠了,因而特別適合在移動設備上使用,SQLite不僅支持標準的SQL 語法,還遵循了資料庫的ACID 事務,所以只要你以前使用過其他的關系型資料庫,就可以很快地上手SQLite,而SQLite 又比一般的資料庫要簡單得多,它甚至不用設定用戶名和密碼就可以使用,Android 正是把這個功能極為強大的資料庫嵌入到了系統當中,使得本地持久化的功能有了一次質的飛躍,
檔案存盤和SharedPreferences存盤畢竟只適用于去保存一些簡單的資料和鍵值對,當需要存盤大量復雜的關系型資料的時候,你就會發現以上兩種存盤方式很難應付得了,比如我們手機的短信程式中可能會有很多個會話,每個會話中又包含了很多條資訊內容,并且大部分會話還可能各自對應了電話簿中的某個聯系人,很難想象如何用檔案或者SharedPreferences 來存盤這些資料量大、結構性復雜的資料吧?但是使用資料庫就可以做得到,那么我們就趕快來看一看,Android 中的SQLite 資料庫到底是如何使用的,
1、需要了解的地方
Android 為了讓我們能夠更加方便地管理資料庫,專門提供了一個SQLiteOpenHelper 幫
助類,借助這個類就可以非常簡單地對資料庫進行創建和升級,首先你要知道SQLiteOpenHelper 是一個抽象類,這意味著如果我們想要使用它的話,
就需要創建一個自己的幫助類去繼承它,SQLiteOpenHelper 中有兩個抽象方法,分別是
onCreate()和onUpgrade(),我們必須在自己的幫助類里面重寫這兩個方法,然后分別在這兩
個方法中去實作創建、升級資料庫的邏輯,SQLiteOpenHelper 中還有兩個非常重要的實體方法, getReadableDatabase() 和
getWritableDatabase(),這兩個方法都可以創建或打開一個現有的資料庫(如果資料庫已存在
則直接打開,否則創建一個新的資料庫),并回傳一個可對資料庫進行讀寫操作的物件,不
同的是,當資料庫不可寫入的時候(如磁盤空間已滿)getReadableDatabase()方法回傳的對
象將以只讀的方式去打開資料庫,而getWritableDatabase()方法則將出現例外,
這里我們希望創建一個名為BookStore.db 的資料庫,然后在這個資料庫中新建一張Book
表,表中有id(主鍵)、作者、價格、頁數和書名等列,創建資料庫表當然還是需要用建表
陳述句的,這里也是要考驗一下你的SQL 基本功了,Book 表的建表陳述句如下所示:
create table Book (
id integer primary key autoincrement,
author text,
price real,
pages integer,
name text)
只要你對SQL 方面的知識稍微有一些了解,上面的建表陳述句對你來說應該都不難吧,
SQLite 不像其他的資料庫擁有眾多繁雜的資料型別,它的資料型別很簡單,integer 表示整型,real 表示浮點型,text 表示文本型別,blob 表示二進制型別,另外,上述建表陳述句中我們還使用了primary key 將id 列設為主鍵,并用autoincrement 關鍵字表示id 列是自增長的,
2、代碼演示
1、創建SQLiteOpenHelper繼承類,例如
package com.example.attendance_demo.DB;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_Employees = "create table employee ("
+ "id text primary key, "
+ "name text unique, "
+ "password text, "
+ "department text, "
+ "post text)";
public static final String CREATE_Depart = "create table Depart ("
+ "id text primary key, "
+ "name text)";
public static final String CREATE_JiXiao = "create table Jixiao ("
+ "num integer primary key autoincrement, "
+ "eid text, "
+ "week text, "
+ "month text, "
+ "grade text, "
+ "quanqin 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_Employees);
db.execSQL(CREATE_Depart);
db.execSQL(CREATE_JiXiao);
Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
2、MainActivity中呼叫
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "Co.db", null, 1);
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
3、寫入:
ContentValues values = new ContentValues();
values.put("id","1");
values.put("name","Admin");
values.put("password","123456");
values.put("department", (byte[]) null);
values.put("post","2");
db.insert("employee",null,values);
values.clear();
values.put("id","2");
…………………………………………………………
db.insert("employee",null,values);
4、查詢并進行密碼驗證
final String user_str = id.getText().toString();
final String psw_str = pwd.getText().toString();
if (user_str.equals("") || user_str.equals("")) {
Toast.makeText(MainActivity.this, "密碼不得為空!", Toast.LENGTH_SHORT).show();
}else {
Cursor cursor = db.query("employee", new String[]{"password","name","post"}, "id=?", new String[]{user_str}, null, null, null);
if(cursor.moveToNext()){
String psw_query=cursor.getString(cursor.getColumnIndex("password"));
name_query = cursor.getString(cursor.getColumnIndex("name"));
partSelector = cursor.getString(cursor.getColumnIndex("post"));
if(psw_str.equals(psw_query)){
db.close();
db2.close();
dbHelper.close();
Toast.makeText(MainActivity.this, "登陸成功,歡迎"+ name_query +"!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "密碼錯誤或用戶不存在!", Toast.LENGTH_SHORT).show();
}
5、寫入listview方法:
MyDatabaseHelper moh = new MyDatabaseHelper(this,"Co.db",null,1);
SQLiteDatabase sd = moh.getReadableDatabase();
ArrayList employeelist = new ArrayList<>();
//掃描資料庫,將資料庫資訊放入studentlist
Cursor cursor = sd.rawQuery("select * from Jixiao",null);
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("num"));
String eid = cursor.getString(cursor.getColumnIndex("eid"));
String grade = cursor.getString(cursor.getColumnIndex("grade"));
String quanqin = cursor.getString(cursor.getColumnIndex("quanqin"));
employeeInfo st = new employeeInfo(id,eid,grade,quanqin); //student_info存一個條目的資料
employeelist.add(st);//把資料庫的每一行加入陣列中
}
//獲取ListView,并通過Adapter把studentlist的資訊顯示到ListView
//為ListView設定一個配接器,getCount()回傳資料個數;getView()為每一行設定一個條目
lv = findViewById(R.id.employee_content_evaluate);
lv.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return employeelist.size();
}
//ListView的每一個條目都是一個view物件
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
//對ListView的優化,convertView為空時,創建一個新視圖;convertView不為空時,代表它是滾出
//螢屏,放入Recycler中的視圖,若需要用到其他layout,則用inflate(),同一視圖,用findViewBy()
if (convertView==null){
view=View.inflate(getBaseContext(),R.layout.listviewadapter,null);
}else {
view = convertView;
}
return view
}
3、寫在最后
最后沒有東西啦
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/399588.html
標籤:其他
上一篇:來自底層碼農的總結
