歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 學生管理系統 之 SQLite數據庫操作

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

日期:2017/3/1 11:08:19   编辑:Linux編程

在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);
}
}

Copyright © Linux教程網 All Rights Reserved