1.创建数据库要用到一个类SQLiteOpenHelper,它是一个抽象类可以创一个类继承他
class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context, String name, CursorFactory factory,int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
+ " text not null, " + BODY + " text not null " + ");";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
生成DBHelper对象是系统生成数据库对象,参数version可以用来控制版本更新,在onCreate方法中可以创建此数据库的表
2.对数据库中表的操作就是通过SQL语句的定义和调用SQLitedatabase对象的execSQL来执行的,如创建表:
String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
+ " text not null, " + BODY + " text not null " + ");";
db.execSQL(sql);
上述创建了一个名为TABLE_NAME(类中定义的字符串常量)的表,表中两列数据一为TITLE另一为BODY
插入数据:
public void insertData()
{
SQLiteDatabase sdb = db.getWritableDatabase();
String sql = "insert into "+ TABLE_NAME+" ("+TITLE+", "+BODY+") values('hellokitty','stronger');";
sdb.execSQL(sql);
}
获得数据:
public void getData()
{
SQLiteDatabase sdb = db.getWritableDatabase();
String[] col = {TITLE,BODY};
Cursor cursor=sdb.query(TABLE_NAME, col, null, null, null, null, null);
cursor.moveToFirst();
int a=cursor.getColumnIndex(BODY);
et.setText("count:"+cursor.getString(a1));
cursor.moveToNext();
int a1=cursor.getColumnIndex(BODY);
et.setText("count:"+cursor.getString(a1));
}
Cursor就像是查询的结果集的指针,moveToNext()方法让其移到下一行,测试时貌似表中有一行默认的数据