Android學習筆記(三資料庫SQLITE的基本操作)

來源:互聯網
上載者:User

SQLITE是android內建的標準資料庫,它支援SQL語句,是一個輕量級的嵌入式資料庫.
學習SQLITE首先需要瞭解一些知識點:
1. SQLiteDatabase
 一個SQLiteDatabase的執行個體代表一個SQLite的資料庫,通過SQLiteDatabase執行個體的一些方法,我們可以執行SQL語句,進行對資料庫的增刪改查操作。 資料庫對於一個應用來說是私人的,並且在一個應用當中,名字也是唯一的。
2. SQLiteOpenHelper
 這是一個抽象類別。當在程式中調用這個類的方法getWritableDatebase()或者getReadableDatebase()方 法的時候,如果當時沒有資料,那麼android系統就會自動產生一個資料庫。對於SQLiteOpenHelper我們通常需要繼承它,並實現它裡面的 3個函數
  (1)onCreate
      在資料庫第一次產生的時候會調用這個方法,一般我們在這個方法裡邊產生資料庫表
  (2)onUpgrade
      當資料庫需要升級的時候,Android系統會自動調用這個方法,一般我們在這個方法裡面刪除資料庫表,並建立新的資料庫表。並且還可以根據應用需求進行其它操作。
  (3)onOpen
      這是當開啟資料庫時的回呼函數,一般也不會用到。
下面來展示一下操作資料庫的具體代碼
public class ActivityMain extends Activity {
 OnClickListener listener1 = null;
 OnClickListener listener2 = null;
 OnClickListener listener3 = null;
 OnClickListener listener4 = null;
 OnClickListener listener5 = null;
 Button button1;
 Button button2;
 Button button3;
 Button button4;
 Button button5;
 DatabaseHelper mOpenHelper;
 private static final String DATABASE_NAME = "dbForTest.db";
 private static final int DATABASE_VERSION = 1;
 private static final String TABLE_NAME = "diary";
 private static final String TITLE = "title";
 private static final String BODY = "body";
 private static class DatabaseHelper extends SQLiteOpenHelper {
  DatabaseHelper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
  @Override
  public void onCreate(SQLiteDatabase db) {
   String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
     + " text not null, " + BODY + " text not null " + ");";
   System.out.print(sql);
   Log.i("haiyang:createDB=", sql);
   db.execSQL(sql);
  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
 }
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  prepareListener();
  initLayout();
  mOpenHelper = new DatabaseHelper(this);
 }
 private void initLayout() {
  button1 = (Button) findViewById(R.id.button1);
  button1.setOnClickListener(listener1);
  button2 = (Button) findViewById(R.id.button2);
  button2.setOnClickListener(listener2);
  button3 = (Button) findViewById(R.id.button3);
  button3.setOnClickListener(listener3);
  button4 = (Button) findViewById(R.id.button4);
  button4.setOnClickListener(listener4);
  button5 = (Button) findViewById(R.id.button5);
  button5.setOnClickListener(listener5);
 }
 private void prepareListener() {
  listener1 = new OnClickListener() {
   public void onClick(View v) {
    CreateTable();
   }
  };
  listener2 = new OnClickListener() {
   public void onClick(View v) {
    dropTable();
   }
  };
  listener3 = new OnClickListener() {
   public void onClick(View v) {
    insertItem();
   }
  };
  listener4 = new OnClickListener() {
   public void onClick(View v) {
    deleteItem();
   }
  };
  listener5 = new OnClickListener() {
   public void onClick(View v) {
    showItems();
   }
  };
 }
 
 private void CreateTable() {
  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
  String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
    + " text not null, " + BODY + " text not null " + ");";
  Log.i("haiyang:createDB=", sql);
  try {
   db.execSQL("DROP TABLE IF EXISTS diary");
   db.execSQL(sql);
   setTitle("資料表成功重建");
  } catch (SQLException e) {
   setTitle("資料表重建錯誤");
  }
 }
 
 private void dropTable() {
  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
  String sql = "drop table " + TABLE_NAME;
  try {
   db.execSQL(sql);
   setTitle("資料表成功刪除:" + sql);
  } catch (SQLException e) {
   setTitle("資料表刪除錯誤");
  }
 }
 
 private void insertItem() {
  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
  String sql1 = "insert into " + TABLE_NAME + " (" + TITLE + ", " + BODY
    + ") values('haiyang', 'android的發展真是迅速啊');";
  String sql2 = "insert into " + TABLE_NAME + " (" + TITLE + ", " + BODY
    + ") values('icesky', 'android的發展真是迅速啊');";
  try {
   Log.i("haiyang:sql1=", sql1);
   Log.i("haiyang:sql2=", sql2);
   db.execSQL(sql1);
   db.execSQL(sql2);
   setTitle("插入兩條資料成功");
  } catch (SQLException e) {
   setTitle("插入兩條資料失敗");
  }
 }
 
 private void deleteItem() {
  try {
   SQLiteDatabase db = mOpenHelper.getWritableDatabase();
   db.delete(TABLE_NAME, " title = 'haiyang'", null);
   setTitle("刪除title為haiyang的一條記錄");
  } catch (SQLException e) {
  }
 }
 
 private void showItems() {
  SQLiteDatabase db = mOpenHelper.getReadableDatabase();
  String col[] = { TITLE, BODY };
  Cursor cur = db.query(TABLE_NAME, col, null, null, null, null, null);
  Integer num = cur.getCount();
  setTitle(Integer.toString(num) + " 條記錄");
 }
}
在上述代碼中
 DataBaseHelper類繼承了SQLieOpenHelper類,並且重寫了onCreate和onUpgrade方法。
 在onCreate方法中我們首先構造了一條SQL語句,然後調用了db.execSQL(sql)執行SQL語句。產生了一個表
 因為目前我們還不需要升級資料庫,所以我們在onUpgrade()函數裡面沒有執行任何操作。
==============================================================================================
下面對應的就是增刪改查方法
主要說下查的方法:
  如前面知識點所說,先建立一個SQLiteDatebase的對象,得到一個可寫的資料庫.
 Sring col[]={TITLE,BODY};
 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
 Cursor cur = db.query(TABLE_NAME, col, null, null, null, null, null);
 這條語句將查詢到的資料放到一個Cursor中。這個Cursor中封裝了這個資料表TABLE_NAME當中的所有條列。下面具體說下query()方法:
 第一個參數是資料庫裡邊表的名字。
 第二個參數是我們想要返回資料包含的列的資訊。如上面代碼所示 我們把列名存放在名為col的數組裡
 第三個參數為selection,相當於SQL語句的where部分,如果想返回所有的資料,那麼就直接設定為null.
 第四個參數為selectionArgs.在selection部分,有可能用到"?",那麼在selectionArgs定義的字串會代替selection中的"?".
 第五個參數為groupBy。定義查詢出來的資料是否分組,如果為null,則說明不需要分組。
 第六個參數為having。相當於SQL語句當中的having部分。
 第七個參數為orderBy。這個就是排序。
最後 Integer num=cur.getCount()語句通過getCount()方法,可以得到Cursor當中資料的個數。
對於Cursor的理解:
Cursor本身是指標的意思。在android中是一個非常有用的介面,通過Cursor我們可以對從資料庫查詢出來的結果集進行隨機的讀寫訪問。
 
一個簡單的對資料庫操作的demo介紹完了,最後需要說明的是 在Android的設計哲學裡鼓勵開發人員使用內部類,這樣不但使用方便,而且執行效率也高。

 

本文出自“haiyang08101”
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.