Android中存储体系介绍,SQLite学习笔记

来源:互联网 发布:中国数据安全法 编辑:程序博客网 时间:2024/05/15 17:14

数据存储

 使用SQLlite数据库
  1. 创建数据库
  private static class DatabaseHelper extends SQLiteOpenHelper {
  DatabaseHelper(Context context) {
                      //创建数据库
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
   Log.d("db", "database create ok..");
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
                        //创建数据表
   String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
     + " text not null, " + BODY + " text not null " + ");";
   Log.i("haiyang:createDB=", sql);
   db.execSQL(sql);
   Log.d("db", "table create ok..");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
 }

  2。程序中创建表
      SQLiteDatabase db = mOpenHelper.getWritableDatabase();
      String sql = "CREATE TABLE diary ( title text not null, body text not null );";
      db.execSQL(sql);  
  3。记录的基本操作

   A.插入记录
      SQLiteDatabase db = mOpenHelper.getWritableDatabase();
      String sql1 = "insert into diary (title,body) values ('hao','haoaho');";
      db.execSQL(sql1);
   B.删除记录
     1.
      SQLiteDatabase db = mOpenHelper.getWritableDatabase();
      db.delete(TABLE_NAME, " title = 'g3'", null);
     2.
      SQLiteDatabase db = mOpenHelper.getWritableDatabase();
      String sql1 = "delete form diary where title='g3'";
      db.execSQL(sql1);
   c.更新记录
     SQLiteDatabase db = mOpenHelper.getWritableDatabase();
      String sql1 = "update diary set body='henhao' where title='g3'";
      db.execSQL(sql1);
   d.查询记录
      SQLiteDatabase db = mOpenHelper.getReadableDatabase();
      String col[] = { BODY,TITLE  };//列名
     String arg[]={"g3"};
      //                       表名  列名列表 条件 条件参数 分组 分组条件 排序 分页        
      Cursor cur = db.query(TABLE_NAME, col, "title='?'", arg, null, null, null);
      Integer num = cur.getCount();//返回查询结果中记录各抒己见
       //循环获取每条数据  
      while(cur.moveToNext())
 {            //或取当前行数据 列名索引号
  title+=","+cur.getString(cur.getColumnIndex(TITLE))+
  ","+cur.getString(cur.getColumnIndex(BODY)) ;
   
 }