您的位置:首页 > 移动开发 > Android开发

Android 学生管理系统 之 SQLite数据库操作

2011-11-04 21:26 309 查看
在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 of
getWritableDatabase()
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 and
onCreate(SQLiteDatabase)
,
onUpgrade(SQLiteDatabase, int, int)
and/or
onOpen(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 call
close()
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 by
getWritableDatabase()
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 to
getWritableDatabase()
may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.

综合构造函数SQLiteOpenHelper和
getWritableDatabase的解释,可以看出SQLiteOpenHelper并不会正真创建一个数据库,只有当数据库不存在时且第一次调用getWritableDatabase或者
getReadableDatabase时才会在外存上程序的数据区data/data/com.bill.studentMng/database下建立数据库,经我测试也确实如此。


还有一般不出意外的话
getReadableDatabase()与
getWritableDatabase() 所返回的的数据库都可以进行读写操作,而不像其名字所说的,不过我一般还是在只进行读操作时用[code]
getReadableDatabase(),进行写操作时用[code]
getWritableDatabase()。

[code]
         
最后要注意的是要及时用close()关闭数据库,不过当你使用query进行查询时一定要先用获得的Cursor将所需要的数据都读出后再关闭数据库,不能获得Cursor后立刻关闭数据库,否则无法读取数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: