在Android上做了個小程序——學生管理系統,下面分享一點開發經驗。
SQLite數據庫操作
Android 提供了 SQLiteOpenHelper 幫助你創建一個數據庫,你只要繼承 SQLiteOpenHelper 類,就可以輕松的創建數據庫。SQLiteOpenHelper 類根據開發應用程序的需要,封裝了創建和更新數據庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現三個方法:
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);
}
}