본문 바로가기

Daily Sample

[Day5] Android SQLite 기본 동작 소스

TITLE : SQLite Sample
Date : 04/16/2010
Writen by Dayyoung
Description :
This is Source that Show Basic action  about SQLite.
Android SQLite 기본 동작 소스
Download : 



SQLite의 open()/drop()/create()/insert()/query()/update()/delete() 를 하는 예제


모듈별로 정리되있기 때문에 고쳐서 그대로 적용도 가능하다.

1. 데이터베이스 오픈

openDatabase(); // 로컬 데이터베이스를 여는 함수

db = SQLiteDatabase.openDatabase(“data/data/org.dayyoung.database/myfriendsDB3″, null, SQLiteDatabase.CREATE_IF_NECESSARY);

실행후 DDMS 탐색기에서 다음과 같은 DB파일이 생성되어 있어야 정상.


2. 테이블 드랍

dropTable();

db.execSQL(“drop table tbIAMigo”)

3. 생성 후 삽입

insertSomeDbData();

db.execSQL(“create table tbIAMIGO(“+”recID integer PRIMARY KEY autoincrement,” +”name text,”+”phone text);”);

로 태이블 생성 후

db.execSQL(“insert into tbIAMIGO(name,phone)”+”values(‘AAA’,’555′);”);
형식으로 데이터 삽입

4. 일반적인 방식의 쿼리호출 (반환값은 쿼리실행결과를 가지고 있는 cusor)

useRawQuery1();

useRawQuery2();
useRawQuery3();

String mySQL = “select count(*) as Total from tbIAMIGO”;
Cursor c1 = db.rawQuery(mySQL, null);

5. 안드로이드 방식(?)의 인자값입력 쿼리호출

useSimpleQuery1();
useSimpleQuery2();
String [] selectColumns = {“name”,”count(*)as TotalSubGroup”};
String whereCondition = “recID>=?”;
String [] whereConditionArgs = {“1″};
String groupBy =”name”;
String having = “count(*) <=4″;
String orderBy = “name”;

Cursor c1 = db.query(“tbIAMIGO”, selectColumns, whereCondition, whereConditionArgs, groupBy, having, orderBy);

6. 반환된 cusor에서 row로 프린트하는 방법

useCursor1();

while(c.moveToNext())
{
columns[0] = Integer.toString((c.getInt(idCol)));
columns[1] = c.getString(nameCol);
columns[2] = c.getString(phoneCol);

txtMsg.append(columns[0]+”|”+columns[1]+”|”+columns[2]+”\n”);
}

7. table 값 변경
updateDB();

theValue =”222″;

db.execSQL(“update tbIAMIGO”
+ ” set name = (name||’XXX’)”
+ ” where phone >= “+theValue+”");

8. 인서트 명령으로 값 삽입

useInsertMethod();

initalValues.put(“name”, “DEF”);
initalValues.put(“phone”, “202″);
rowPosition = (int)db.insert(“tbIAMIGO”, null, initalValues);

9. 특정 값 변경

useUpdateMethod();

String[] whereArgs = {“2″,”7″};

ContentValues updValues = new ContentValues();
updValues.put(“name”, “Maria”);

int recAffected = db.update(“tbIAMIGO”, updValues, “recID > ? and recID <?”, whereArgs);

10. 특정값 삭제
useDeleteMethod();

String[] whereArgs = {“2″,”7″};

int recAffected = db.delete(“tbIAMIGO”, “recID > ? and recID <?”, whereArgs);

——————————————————————————————-

암호같은 문자 치환이나 케스팅이 난해할 수 있으나 SQLite는 최근 모바일OS에서 많이 쓰이고있으니  천천히라도 이해해야한다.
Creative Commons License
이 저작물은 크리에이티브 커먼즈 저작자표시 3.0 Unported 라이선스에 따라 이용할 수 있습니다.