Android 學生管理系統 之 SQLite數據庫操作

           在Android上做了個小程序——學生管理系統,下面分享一點開發經驗。

SQLite數據庫操作

           Android 提供了 SQLiteOpenHelper 幫助你創建一個數據庫,你只要繼承 SQLiteOpenHelper 類,就可以輕鬆的創建數據庫。SQLiteOpenHelper 類根據開發應用程序的需要,封裝了創建和更新數據庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現三個方法:

  • 構造函數,調用父類 SQLiteOpenHelper 的構造函數。這個方法需要四個參數:上下文環境(Context)(例如,一個 Activity),數據庫名字,一個可選的遊標工廠(CursorFactory)(通常是 Null),一個代表你正在使用的數據庫模型版本的整數。
  • onCreate()方法,它需要一個 SQLiteDatabase 對象作爲參數,根據需要對這個對象填充表和初始化數據。
  • onUpgrage() 方法,它需要三個參數,一個 SQLiteDatabase 對象,一箇舊的版本號和一個新的版本號,這樣你就可以清楚如何把一個數據庫從舊的模型轉變到新的模型。
        下面是我的繼承了SQLiteOpenHelper 的SQLiteAdapter類

package com.bill.studentMng;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteAdapter extends SQLiteOpenHelper
{
    private String TableName;
    private SQLiteDatabase db;
    private static final String ID = "ID";
    private static final String NAME = "NAME";
    private static final String SEX = "SEX";
    private static final String CLASS = "CLASS";
    //構造函數
    public SQLiteAdapter(Context context, String DBName, String TableName, CursorFactory factory,int version)
    {
        super(context, DBName, factory, version);
        this.TableName = TableName;
    }
    //
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // TODO Auto-generated method stub
        Log.i("TAG","CreatDB");
        String sql = "create table STUDENT(ID text primary key,NAME text,SEX text,CLASS text);";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        String sql =" DROP TABLE IF EXISTS "+TableName;
        db.execSQL(sql);
        onCreate(db);
    }

    public void open(String mode)
    {
        if(mode.equals("w"))
        {
            //打開一個可寫數據庫
            db = this.getWritableDatabase();
        }
        else
        {
            //打開一個可讀數據庫
            db = this.getReadableDatabase();
        }
    }
    
    public void close()
    {
        db.close();//關閉數據庫        
    }
    
    public Cursor select()
    {
        Cursor cursor = db.query(TableName, null, null, null, null, null, null);
        return cursor;
    }
    
    public long insert(String id, String name, String sex, String sclass)
    {
        
        ContentValues cv = new ContentValues();
        cv.put(ID, id);
        cv.put(NAME, name);
        cv.put(SEX, sex);
        cv.put(CLASS, sclass);
        long row = db.insert(TableName, null, cv);
        return row;
    }
    
    public void remove(String key, String value)
    {
        db.execSQL("DELETE FROM "+TableName+" WHERE "+key+"="+value);
    }
}

         下面是我的Student類,其中方法public long AddToDB(),public void RemoveFromDB(),public List<Student> Qurey(Context context)分別實現了將學生數據加入數據庫,從數據庫刪除,以及從數據庫讀出的功能:

package com.bill.studentMng;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class Student
{
    public static final String TableName = "STUDENT";
    public static final String DBName = "STUDENT";
    private String Id;
    private String Name;
    private String Sex;
    private String sClass;
    private SQLiteAdapter SqlDB;
    private Cursor cursor;
    private List<Student> list = new ArrayList<Student>();
    public Student(Context context, String id, String name, String sex, String sclass)
    {
        Id = id;
        Name = name;
        Sex = sex;
        sClass = sclass;
        SqlDB = new SQLiteAdapter(context, DBName,TableName, null, 1);
    }
    public Student(Context context)
    {
        SqlDB = new SQLiteAdapter(context, DBName,TableName, null, 1);
    }
    
    public void setDB(SQLiteAdapter db)
    {
        this.SqlDB = db;
    }
    
    public String getId()
    {
        return Id;
    }
    public Student setId(String id)
    {
        Id = id;
        return this;
    }
    public String getName()
    {
        return Name;
    }
    public Student setName(String name)
    {
        Name = name;
        return this;
    }
    public String getSex()
    {
        return Sex;
    }
    
    public Student setSex(String sex)
    {
        Sex = sex;
        return this;
    }
    
    public String getsClass()
    {
        return sClass;
    }
    
    public Student setClass(String sclass)
    {
        sClass = sclass;
        return this;
    }

    public long AddToDB()
    {
        Log.i("TAG","WRITE");
        SqlDB.open("w");
        long result = SqlDB.insert(Id, Name, Sex, sClass);
        SqlDB.close();
        return  result;
    }
    
    public void RemoveFromDB()
    {
        SqlDB.open("w");
        SqlDB.remove("ID",Id);
        SqlDB.close();
    }
    
    public List<Student> Qurey(Context context)
    {
        Log.i("TAG","READ");
        SqlDB.open("w");
        cursor =  SqlDB.select();
        while(cursor.moveToNext())
        {
            Student student = new Student(context,cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3));
            list.add(student);
        }
        SqlDB.close();
        return list;
    }
}

         對於構造函數SQLiteOpenHelper(Context context,String name, SQLiteDatabase.CursorFactory factory, int version),官方是這樣介紹的:

          Create a helper object to create, open, and/or manage a database. This method always returns very quickly. The database is not actually created or opened until one ofgetWritableDatabase() or getReadableDatabase() is called.

          再看看getWritableDatabase()的官方介紹:

        Create and/or open a database that will beused for reading and writing. The first time this is called, the database will be opened andonCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/oronOpen(SQLiteDatabase) will be called.

        Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to callclose() when you no longer need the database.) Errors such as bad permissions or a full disk may cause this method to fail, but future attempts may succeed if the problem is fixed.

          getReadableDatabase():

          Create and/or open a database. This will be the same object returned bygetWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call togetWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future. 

          綜合構造函數SQLiteOpenHelpergetWritableDatabase的解釋,可以看出SQLiteOpenHelper並不會正真創建一個數據庫,只有當數據庫不存在時且第一次調用getWritableDatabase或者getReadableDatabase時纔會在外存上程序的數據區data/data/com.bill.studentMng/database下建立數據庫,經我測試也確實如此。

       還有一般不出意外的話getReadableDatabase()getWritableDatabase() 所返回的的數據庫都可以進行讀寫操作,而不像其名字所說的,不過我一般還是在只進行讀操作時用getReadableDatabase(),進行寫操作時用getWritableDatabase()

          最後要注意的是要及時用close()關閉數據庫,不過當你使用query進行查詢時一定要先用獲得的Cursor將所需要的數據都讀出後再關閉數據庫,不能獲得Cursor後立刻關閉數據庫,否則無法讀取數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章