android基本的資料庫建立和使用

來源:互聯網
上載者:User

標籤:android   style   class   blog   code   java   

  android的四大組件中就有Content Provider,對其他應用,提供自己的資料,所以,一般情況下,android應用不需要提供content provider。

  1.  簡單的資料庫表單欄位聲明:

   MySqlName.java

    

        public static final int VERSION = 1;        public static final String DBNAME = "mydb";                      /*     * 連絡人詳情資料庫     */    public class Contacts{        public static final String TableName="contacts";                public static final String Id="cId";//連絡人的uri                public static final String Number="number";                public static final String Name="name";    }

一般一張表,寫一個內部類,內部類的變數是資料庫中的列。這個檔案寫成這樣子就可以了。

  2. 建立資料庫

  MySql.java

  

public class Mysql extends SQLiteOpenHelper{

public Mysql(Context context) { super(context,Mysqlname.DBNAME, null, Mysqlname.VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub /* * 建立人員表單 */ db.execSQL("create table "+Mysqlname.Contacts.TableName+"(" + Mysqlname.Contacts.Id+" integer primary key autoincrement not null,"+ Mysqlname.Contacts.Number+" text ," + Mysqlname.Contacts.Name+" text );"
  
        ); }
}

這樣,在這個資料庫建立就完成了,但是除了建立工作,還需要對外提供一些方法;

  3.  操作

  • 查詢 
SQLiteDatabase db = this.getWritableDatabase(); Cursor cr =db.query(Mysqlname.Contact.TableName, null, Mysqlname.Contact.Id+"=?", new String[]{id}, null, null, null);

如果需要使用這個cr的內的值,需要:

if(cr!=null&&cr.getCount()>0&&cr.moveToFirst()){String name = cr.getString(cr.getColumnIndex(Mysqlname.Contact.Name));}

這裡必須要movetofirst,不然會報錯。

  • 插入
db.insert(Mysqlname.Contact.TableName, Mysqlname..Contact.ID, values)

 

  • 刪除
db.delete(Mysqlname.Contact.TableName, Mysqlname.Contact.Id+"=? and "+Mysqlname.Contact.NAME+"=?", new String[]{id,name});

 

  • 修改
db.update(Mysqlname.Contact.TableName, values, Mysqlname.Contact.Id+"=?", new String[]{id})

 

 

注意,以上的db ,Cursor,在使用完畢後,必須及時調用db.close(),cr.close();

  

相關文章

聯繫我們

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