[android] 안드로이드에서 SQLite 데이터베이스 사용
안드로이드 앱에서 데이터를 저장하고 관리하기 위해 SQLite 데이터베이스를 사용할 수 있습니다. SQLite는 안드로이드 플랫폼에 내장되어 있어 가벼우면서도 효율적으로 데이터를 저장할 수 있는 오픈 소스 데이터베이스 엔진입니다. 이번 포스트에서는 안드로이드 앱에서 SQLite 데이터베이스를 사용하는 방법에 대해 알아보겠습니다.
1. SQLite 데이터베이스 생성
SQLite 데이터베이스를 사용하기 위해서는 다음과 같은 단계를 따릅니다.
1-1. 데이터베이스 생성 도우미 클래스 생성
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDatabase";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS MyTable");
onCreate(db);
}
}
1-2. 데이터베이스 인스턴스 생성
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
2. 데이터 CRUD 작업
2-1. 데이터 추가
ContentValues values = new ContentValues();
values.put("name", "John");
db.insert("MyTable", null, values);
2-2. 데이터 조회
Cursor cursor = db.query("MyTable", null, null, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
// do something with the data
}
cursor.close();
}
2-3. 데이터 수정
ContentValues values = new ContentValues();
values.put("name", "Jane");
db.update("MyTable", values, "id = ?", new String[]{"1"});
2-4. 데이터 삭제
db.delete("MyTable", "id = ?", new String[]{"1"});
안드로이드에서 SQLite 데이터베이스를 사용하는 방법에 대해 간략히 살펴보았습니다. SQLite를 효과적으로 사용하여 안드로이드 앱에서 데이터를 저장하고 관리할 수 있습니다.
참고 자료
- 안드로이드 공식 문서: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
- 박성택, 『안드로이드 프로그래밍 정복: 안드로이드 스튜디오를 활용한 안드로이드 프로그래밍 입문』, 한빛미디어, 2018.
더 자세한 내용은 상기 참고 자료를 참조하시기 바랍니다.