2013년 7월 15일 월요일

[Android] SQLiteOpenHelper를 이용한 Database 생성과 커리문 실행

1. DB 생성과 커리 실행 방법
- SQLiteOpenHelper 클래스는 DB를 (생성||열기||업데이트)위해 필요한 일들을 도와주는 역활을 한다.

1.1 데이터 베이스 생성 혹은 열기위해 필요한 객체를 생성
- public DataBaseHelper(Context context, String name, CursorFactory factory, int version)

1.2 처음에 DB가 생성될때 호출됨
- public void onCreate(SQLiteDatabase database)

1.3 DB가 존재할때 DB를 열때 호출됨
- public void onOpen(SQLiteDatabase database)

1.4 DB가 존재할때 DB버전이 바뀌면 호출됨
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

2. 예제 
android version = jelly bean
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MyDataBaseHelperActivity extends Activity {
 public static final String tableName = "CUSTOMER";
 Button button1;
 Button button2;
 Button button3;
 Button button4;
 TextView text1;
 DataBaseHelper helper;
 SQLiteDatabase database;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  button1 = (Button) findViewById(R.id.button1);
  button2 = (Button) findViewById(R.id.button2);
  //button3 = (Button) findViewById(R.id.button3);
  //button4 = (Button) findViewById(R.id.button4);
  text1 = (TextView) findViewById(R.id.text1);

  // 디비 생성
  button1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    createDatabase();
   }
  });
  
  // 커리 실행
  button2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    queryData();
   }
  });
 }

 private void createDatabase() {
  int version = 1;
  String name = "customer.db";
  // database = openOrCreateDatabase(name, MODE_WORLD_WRITEABLE, null);
  
  //헬퍼를 이용해 디비생성방법
  helper = new DataBaseHelper(getApplicationContext(), name, null, version);
  database = helper.getWritableDatabase();
 }

 private void queryData() {
  String sql = "select id,name,age from " + tableName + " where age >18";
  
  // 데이터를 받을땐 커서로 받는다
  Cursor cursor = database.rawQuery(sql, null);

  // cursor.getcount() 레코드 갯수
  // cursor.moveToNext() 다음 레코드를 조회
  // cursor.getString() 칼럼데이타 조회
  if (cursor != null) {
   int count = cursor.getCount();
   text1.append("데이터를 조회햇어요. 레코드 갯수" + count + "\n");

   for (int i = 0; i < count; i++) {
    cursor.moveToNext();
    String name = cursor.getString(1);
    text1.append("데이터 #" + i + ":" + name + "\n");
   }
  }
 }

 class DataBaseHelper extends SQLiteOpenHelper {

  // 데이터베이스를 생성할때 필요한 생성자
  // context = 불러올 액티비티
  // name = 데이터베이스 이름
  // factory = ??
  // version = 데이터베이스 버전
  public DataBaseHelper(Context context, String name,
    CursorFactory factory, int version) {
   super(context, name, factory, version);
  }

  // 데이터베이스를 처음 생성할때 불려지는 메서드 생성되있으면 호출되지않는다.
  @Override
  public void onCreate(SQLiteDatabase database) {
   createTable(database);
   insertData(database);
   text1.append("헬퍼를 이용해 데이터베이스를 생성 했어요.\n");
  }

  // 데이터베이스가 생성되거나 존재할때 데이터베이스를 여는 메서드
  @Override
  public void onOpen(SQLiteDatabase database) {
   text1.append("헬퍼를 이용해 데이터베이스를 오픈 했어요.\n");
  }

  // 데이터베이스가 업그레이드 될때 호출되는 메서든
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   text1.append("헬퍼를 이용해 데이터베이스를 업그레이드 했어요.\n");
  }

  private void createTable(SQLiteDatabase database) {
   String sql = "create table " + tableName + "(id text,name text,age integer)";
   try {
    // sql 실행하는 메서드
    database.execSQL(sql);
    text1.append("테이블을 만들었어요\n");
   } catch (Exception e) {
    text1.append("테이블 만들때 예외\n");
    e.printStackTrace();
   }
  }

  private void insertData(SQLiteDatabase database) {
   // 데이타베이스 트렌젝션 시작
   database.beginTransaction();
   try {
    String sql = "insert into " + tableName + "(id,name,age)" + " values('100','홍길동',21)";

    // sql 실행하는 메서드
    database.execSQL(sql);

    sql = "insert into " + tableName + "(id,name,age)" + " values('200','소녀시대',19)";
    
    // sql 실행하는 메서드
    database.execSQL(sql);
    
    // 데이타베이스 트렌젝션 성공
    database.setTransactionSuccessful();
   } catch (Exception e) {
    text1.append("데이터 추가할 때 예외" + e.getMessage() + "\n");
    e.printStackTrace();
   } finally {
    
    // 데이타베이스 트렌젝션 끝 이것은 꼭 해줘야한다.
    database.endTransaction();
   }

   text1.append("데이터를 넣었어요\n");
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.my_data_base_helper, menu);
  return true;
 }
}

댓글 없음:

댓글 쓰기