Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android SQLite 入門:編寫 SQL 語句操作資料庫(慕課筆記)

編輯:關於 Android 開發

Android SQLite 入門:編寫 SQL 語句操作資料庫(慕課筆記)

本文記錄了 Android 常用資料儲存方式之一 SQLite 的學習與操作重點。

0. 視頻地址:https://www.imooc.com/video/3382

1. 每個程式都有自己的資料庫,預設情況下彼此互不干擾。

1)建立一個資料庫並打開:

SQLiteDatabase db=openOrCreateDatabase("user.db",MODE_PRIVATE,null);

2)使用游標 cursor 儲存查詢結果,可理解為類似 list 的集合。

3)使用完畢後必須釋放游標。

2. 具體程式碼:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 // 每個程式都有自己的資料庫,預設情況下彼此互不干擾
 // 1. 建立一個資料庫並打開
 SQLiteDatabase db=openOrCreateDatabase("user.db",MODE_PRIVATE,null);
 db.execSQL("create table if not exists usertb(_id integer primary key autoincrement," +
 "name text not null,age integer not null,sex text not null)");
 // 建立用戶表,包括 _id 主鍵、姓名、年齡、性別
 db.execSQL("insert into usertb(name,age,sex)values('張三','男',26)");
 db.execSQL("insert into usertb(name,age,sex)values('劉明','男',22)");
 db.execSQL("insert into usertb(name,age,sex)values('於思','女',21)");
 // 2. 使用游標 cursor 儲存查詢結果,可理解為 list
 Cursor c=db.rawQuery("select * from usertb",null);
 if(c!=null){
 while(c.moveToNext()){
 Log.i("info","_id:"+c.getInt(c.getColumnIndex("_id")));
 Log.i("info","name:"+c.getString(c.getColumnIndex("name")));
 Log.i("info","sex:"+c.getString(c.getColumnIndex("sex")));
 Log.i("info","age:"+c.getInt(c.getColumnIndex("age")));
 Log.i("info","!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
 }
 c.close();// 3. 釋放游標
 }
 db.close();
 }
}

3. 運行結果:

4. 知識點小記:

1)可使用工具 navicat 打開並查看 db 格式檔案,檢視自己建立的用戶表。

2)游標 cursor 相關操作:

小結:SQLite 是 Android 內建的輕量級關聯式資料庫,透過 openOrCreateDatabase 建立資料庫、execSQL 執行建表與插入、rawQuery 搭配 Cursor 遍歷結果,就能完成基本的資料操作。切記使用完畢後要記得釋放游標與資料庫連線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved