본문 바로가기

안드로이드

andrid DB 예제

public void insertDB(String alarmTime, String idx) {

WordDBHelper mHelper = new WordDBHelper(AptAlarmActivity.this);

SQLiteDatabase db = null;

try {

db = mHelper.getWritableDatabase();

ContentValues row;

row = new ContentValues();

row.put("idx", idx);

row.put("pushchk", "true");

row.put("pushtime1", "true");

row.put("pushtime2", "false");

row.put("alarmtime", alarmTime);

db.insert("alalmlist", null, row);

} catch (Exception e) {

Log.e("Thread", "Insert Error", e);


} finally {

mHelper.close();

db.close();

}

}


private void selectDB() {

Cursor monthCursor;

WordDBHelper mHelper = new WordDBHelper(AptAlarmActivity.this);

SQLiteDatabase db = null;

String upSql = "SELECT idx,  pushchk, pushtime1,pushtime2,alarmtime FROM alalmlist";

try {

db = mHelper.getWritableDatabase();

db.beginTransaction();

monthCursor = db.rawQuery(upSql, null);


while (monthCursor.moveToNext()) {

String idx = monthCursor.getString(0);

int idxs = Integer.parseInt(idx);

String pushchk = monthCursor.getString(1);

String pushtime1 = monthCursor.getString(2);

String pushtime2 = monthCursor.getString(3);

String alarmtime = monthCursor.getString(4);



}

db.setTransactionSuccessful();

} catch (Exception e) {

Log.e("Thread", "select Error", e);


} finally {

db.endTransaction();

mHelper.close();

}

}


public void updateDB(int id, boolean pushTag, String time) {

WordDBHelper mHelper = new WordDBHelper(AptAlarmActivity.this);

SQLiteDatabase db = null;

try {

db = mHelper.getWritableDatabase();

ContentValues row;

row = new ContentValues();

String strFilter = "idx=" + Integer.toString(id);

row.put("pushchk", Boolean.toString(pushTag));

row.put("pushtime1", Boolean.toString(pushTag));

row.put("alarmtime", time);


db.update("alalmlist", row, strFilter, null);

} catch (Exception e) {

Log.e("Thread", "Insert Error", e);


} finally {

mHelper.close();

db.close();

}


}


private void deleteDB(String idx) {

WordDBHelper mHelper = new WordDBHelper(FragMentZzim.this);

try {

SQLiteDatabase db = mHelper.getWritableDatabase();

db.delete("favorlist", "favoridx='" + idx + "'", null);

} catch (Exception e) {

Log.e("Thread", "Insert Error", e);


} finally {

mHelper.close();

}

}


class WordDBHelper extends SQLiteOpenHelper {


public WordDBHelper(Context context) {

super(context, "mbc.db", null, 2);

}


@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE favorlist ( " +"_id INTEGER PRIMARY KEY AUTOINCREMENT, "

+ "favoridx TEXT,  recomidx TEXT , temp Text);");

db.execSQL("CREATE TABLE recentlist ( " +"_id INTEGER PRIMARY KEY AUTOINCREMENT, "

+ "favoridx TEXT,  recomidx TEXT , temp Text);");

}


@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE  favorlist");

onCreate(db);


}

}