Arthur 2011-11-05
在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);
}
}