Android的SQLite使用執行個體

來源:互聯網
上載者:User

SQLite介紹

SQLite是輕量級的、嵌入式的、關係型資料庫,目前已經在iPhone、Android等手機系統中使用,SQLite可移植性好,很容易使用,很小,高效而且可靠。SQLite嵌入到使用它的應用程式中,它們共用相同的進程空間,而不是單獨的一個進程。從外部看,它並不像一個RDBMS,但在進程內部,它卻是完整的,自自主資料庫引擎。

在android中當需要操作SQLite資料庫的時候需要得到一個SQLiteOpenHelper對象,而SQLiteOpenHelper是一個抽象類別,使用者需要繼承這個類,並實現該類中的一些方法。

1、繼承SQLiteOpenHelper之後就擁有了以下兩個方法:

◆getReadableDatabase() 建立或者開啟一個查詢資料庫

◆getWritableDatabase()建立或者開啟一個可寫資料庫

◆他們都會返回SQLiteDatabase對象,使用者通過得到的SQLiteDatabase對象進行後續操作

2、同時使用者還可以覆蓋以下回呼函數,再對資料庫進行操作的時候回調以下方法:

◆onCreate(SQLiteDatabase):在資料庫第一次建立的時候會調用這個方法,一般我們在這個方法裡邊建立資料庫表。

◆onUpgrade(SQLiteDatabase,int,int):當資料庫需要修改的時候,Android系統會主動的調用這個方法。一般我們在這個方法裡邊刪除資料庫表,並建立新的資料庫表,當然是否還需要做其他的操作,完全取決於應用程式的需求。

◆onOpen(SQLiteDatabase):這是當開啟資料庫時的回呼函數,一般也不會用到。

需要注意

1、在SQLiteOepnHelper的子類當中,必須有以下該建構函式

public DatabaseHelper(Context context, String name, CursorFactory factory,     int version) {    //必須通過super調用父類當中的建構函式    super(context, name, factory, version);  }  

為了方便,也可以建立其它的建構函式,含二個參數或者三個參數的。

2、函數public void onCreate(SQLiteDatabase db)是在調用getReadableDatabase()或者是getWritableDatabase()第一次建立資料庫的時候執行,實際上是在第一次得到SQLiteDatabse對象的時候,才會調用這個方法.

public void onCreate(SQLiteDatabase db) {    System.out.println("create a Database");    //execSQL函數用於執行SQL語句    db.execSQL("create table user(id int,name varchar(20))");  }  

在向資料庫的表中插入記錄時,需要先將資料包含在一個ContentValues中,向該對象當中插入索引值對,其中鍵是列名,值是希望插入到這一列的值,值必須和資料庫當中的資料類型一致。接著調用Databasehelper的getWritableDatabase方法來獲得可以寫入的Databasehelper對象,再向其中insert記錄。注意調用DatabaseHelper對象的insert,update或者query方法的參數的傳遞。

另外執行query方法後,返回的是一個Cursor遊標,遊標最開始指向的是記錄集合中第一行的上一行,因此首先需要先調用cursor.next()將遊標移動到記錄集合的第一行,接著再擷取資料即可。

public class SQLiteActivity extends Activity {        /** Called when the activity is first created. */         private Button createButton;          private Button insertButton;          private Button updateButton;          private Button updateRecordButton;            private Button queryButton;           @Override         public void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);               setContentView(R.layout.main);                createButton = (Button)findViewById(R.id.createDatabase);             updateButton = (Button)findViewById(R.id.updateDatabase);             insertButton = (Button)findViewById(R.id.insert);             updateRecordButton = (Button)findViewById(R.id.update);               queryButton = (Button)findViewById(R.id.query);               createButton.setOnClickListener(new CreateListener());                updateButton.setOnClickListener(new UpdateListener());                insertButton.setOnClickListener(new InsertListener());                updateRecordButton.setOnClickListener(new UpdateRecordListener());                queryButton.setOnClickListener(new QueryListener());          }         class CreateListener implements OnClickListener{              @Override             public void onClick(View v) {                 //建立一個DatabaseHelper對象                    DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_mars_db");                 //只有調用了DatabaseHelper對象的getReadableDatabase()方法,或者是getWritableDatabase()方法之後,才會建立,或開啟一個資料庫                    SQLiteDatabase db = dbHelper.getReadableDatabase();               }         }         class UpdateListener implements OnClickListener{                    @Override             public void onClick(View v) {                 DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_mars_db",2);                   SQLiteDatabase db = dbHelper.getReadableDatabase();               }                       }         class InsertListener implements OnClickListener{                    @Override             public void onClick(View v) {                 //產生ContentValues對象                   ContentValues values = new ContentValues();                   //想該對象當中插入索引值對,其中鍵是列名,值是希望插入到這一列的值,值必須和資料庫當中的資料類型一致                    values.put("id", 1);                  values.put("name","zhangsan");                    DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_mars_db",2);                   SQLiteDatabase db = dbHelper.getWritableDatabase();                   //調用insert方法,就可以將資料插入到資料庫當中                   db.insert("user", null, values);              }         }         //更新操作就相當於執行SQL語句當中的update語句          //UPDATE table_name SET XXCOL=XXX WHERE XXXXCOL=XX...           class UpdateRecordListener implements OnClickListener{                      @Override             public void onClick(View arg0) {                  // TODO Auto-generated method stub                    //得到一個可寫的SQLiteDatabase對象                 DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_mars_db");                 SQLiteDatabase db = dbHelper.getWritableDatabase();                   ContentValues values = new ContentValues();                   values.put("name", "zhangsanfeng");                   //第一個參數是要更新的表名                    //第二個參數是一個ContentValeus對象                 //第三個參數是where子句                   db.update("user", values, "id=?", new String[]{"1"});             }         }         class QueryListener implements OnClickListener{                     @Override             public void onClick(View v) {                 System.out.println("aaa------------------");                  Log.d("myDebug", "myFirstDebugMsg");                                    DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_mars_db");                 SQLiteDatabase db = dbHelper.getReadableDatabase();                   Cursor cursor = db.query("user", new String[]{"id","name"}, "id=?", new String[]{"1"}, null, null, null);                 while(cursor.moveToNext()){                       String name = cursor.getString(cursor.getColumnIndex("name"));                        System.out.println("query--->" + name);                   }             }         }               }

附:

sqlite 中判斷某個表是否存在的方法,貼出來供大家參考

   /**     * 判斷某張表是否存在     * @param tabName 表名     * @return     */    public boolean tabbleIsExist(String tableName){            boolean result = false;            if(tableName == null){                    return false;            }            SQLiteDatabase db = null;            Cursor cursor = null;            try {                    db = this.getReadableDatabase();                    String sql = "select count(*) as c from "+AppConstant.DataBaseName+" where type ='table' and name ='"+tableName.trim()+"' ";                    cursor = db.rawQuery(sql, null);                    if(cursor.moveToNext()){                            int count = cursor.getInt(0);                            if(count>0){                                    result = true;                            }                    }                                } catch (Exception e) {                    // TODO: handle exception            }                            return result;    }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.