1.编写DataBaseOpenHelper 继承SQLiteOpenHelper
完成创建、打开数据库及各种数据库操作。 |
public class DataBaseOpenHelper extends SQLiteOpenHelper {
public DataBaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists person("
+ "id integer primary key,"
+ "name varchar(20),"
+ "brith DateTime)");
db.execSQL("create table if not exists teacher("
+ "id integer primary key,"
+ "name varchar(20),"
+ "course varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
2.TeacherDaoImpl teacher表的数据库访问类 ,完成数据的相关操作。
package com.fullwisdom.sqllite.dao;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.fullwisdom.sqllite.DataBaseOpenHelper;
import com.fullwisdom.sqllite.beans.Teacher;
public class TeacherDaoImpl {
private DataBaseOpenHelper databaseHelper;
public TeacherDaoImpl(DataBaseOpenHelper databaseHelper){
this.databaseHelper = databaseHelper;
}
public long save(Teacher t){
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", t.getName());
values.put("course", t.getCourse());
long rowid = db.insert("teacher", null, values);
return rowid;
}
public Teacher find(int id){
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(true, "teacher", new String[]{"id","name","course"},"id=?",
new String[]{id+""}, null, null, null, null);
if(!cursor.moveToFirst()){
return null;
}
int pid = cursor.getInt(cursor.getColumnIndex("id"));
String pname = cursor.getString(cursor.getColumnIndex("name"));
Teacher t = new Teacher();
t.setId(pid);
t.setName(pname);
return t;
}
}