1.创建数据库
// 创建数据库
public class MyOpenHelper extends SQLiteOpenHelper {
private static final int version = 1;
public MyOpenHelper(Context context) {
super(context, "cgh.db", null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE person (_id INTEGER PRIMARY KEY, name varchar(20), age INTEGER);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
2.对相应的类写增删改查
// 数据操作
public class PersonService {
private static final String tag = "PersonService";
MyOpenHelper helper;
public PersonService() {
helper = new MyOpenHelper(Ch05Ex06.this);
}
public void save(Person person) {
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "insert into person (name , age ) values (?,?)";
db.execSQL(sql , new Object[]{person.name , person.age});
}
public void find(){
SQLiteDatabase db = helper.getReadableDatabase();
String sql = "select * from person";
Cursor cursor = db.rawQuery(sql, null);
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
//String age = cursor.getColumnName(cursor.getColumnIndex("age"));
Log.e(tag, name);
}
}
}