android下建立資料庫學習筆記

來源:互聯網
上載者:User

標籤:

##在Android中建立一個資料庫##

###步驟###

1、建立一個類繼承SQLiteOpenHelper並在類中重寫父類的構造方法、onCreate方法、onGrade方法(資料庫的版本只能升級,不能降級)

###資料庫增刪改查方法##
    public void add(View view){
        SQLiteDatabase db = sql.getWritableDatabase();
        //Random random = new Random();    
        //在資料庫中增加一條資料
        db.execSQL("insert into info (name,phone) values (?,?)", new Object[]{"張三","123456"});
        db.execSQL("insert into info (name,phone) values (?,?)", new Object[]{"李四","654321"});
        Toast.makeText(this,"add successfully!",Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void delete(View view){
        SQLiteDatabase db = sql.getWritableDatabase();
        //在資料庫中刪除指定資料
        db.execSQL("delete from info where name=?", new Object[]{"張三"});
        Toast.makeText(this,"delete successfully!",Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void upgrade(View view){
        SQLiteDatabase db = sql.getWritableDatabase();
        //在資料庫中修改指定資料
        db.execSQL("update info set phone=? where name=?", new Object[]{"111111","李四"});
        Toast.makeText(this,"upgrade successfully!",Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void checkAll(View view){
        SQLiteDatabase db = sql.getReadableDatabase();
        //查詢資料庫並返回遊標集cursor
        Cursor cursor = db.rawQuery("select * from info", null);
        //建立List集合
        List<Person>list = new ArrayList<Person>();
        //通過while迴圈遍曆資料庫資料
        while(cursor.moveToNext()){
            Person person = new Person();
            person.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            person.setName(cursor.getString(cursor.getColumnIndex("name")));
            person.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            list.add(person);
            person=null;
        }
        cursor.close();
        //遍曆List集合
        for(Person p:list){
            System.out.println(p.toString());
        }
        Toast.makeText(this,"checkAll successfully!",Toast.LENGTH_SHORT).show();
        db.close();
    }

android下建立資料庫學習筆記

聯繫我們

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