2012年6月6日水曜日

データベース・アクセス




    private final static String PDB_NAME ="product.db";//DB名
    private final static String PDB_TABLE="product";   //テーブル名
    private final static int    PDB_VERSION=1;      //バージョン
    private static SQLiteDatabase pdb;      //データベースオブジェクト


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        //データベースオブジェクトの取得
        PDBHelper pdbHelper=new PDBHelper(this);
        pdb=pdbHelper.getWritableDatabase();

  }


    //DB検索
    private void readDB(String id) throws Exception {
    //idで検索
        Cursor c=pdb.query(PDB_TABLE,new String[]{"id","Name","Category","Price"},
            "id='" + id + "'",null,null,null,null);
        if (c.getCount()==0) throw new Exception();
        c.moveToFirst(); //最初に一致したもの
                               //順番に取り出す場合は、c.moveToNext(); で次のレコードへ

        //DBから取り出し
        String id   =c.getString(0);
        String name   =c.getString(1);
    String category   =c.getString(2);
        String price   =c.getString(3);

        c.close();
    }    

   //DBへの書き込み
    private void writeDB(String id,String Name,String Cate,String Pr) throws Exception {
        ContentValues values=new ContentValues();
        values.put("id",id);
        values.put("Name",Name);
        values.put("Category",Cate);
        values.put("Price",Pr);

        //idの同じレコードを更新
        int colNum=db.update(DB_TABLE,values,"id='" + id + "'" ,null);

        //新しいidなら追加
        if (colNum==0) {
        db.insert(DB_TABLE,"",values);
        ((TextView) findViewById(R.id.Message)).setText("1レコード追加しました");
        }else{
        ((TextView) findViewById(R.id.Message)).setText("1レコード更新しました");
        }
    }



//データベースヘルパーの定義
private static class PDBHelper extends SQLiteOpenHelper {
    //データベースヘルパーのコンストラクタ
    public PDBHelper(Context context) {
        super(context,PDB_NAME,null,PDB_VERSION);
    }
   
    //データベースの生成
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table if not exists "+
            PDB_TABLE+"(id text primary key,Name text,Category text,Price text)");
    }

    //データベースのアップグレード
    @Override
    public void onUpgrade(SQLiteDatabase db,
        int oldVersion,int newVersion) {
        db.execSQL("drop talbe if exists "+PDB_TABLE);
        onCreate(db);
    }
}

0 件のコメント:

コメントを投稿