ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • DB SQLite (insert/select)
    안드로이드/학습&강좌 2011. 8. 2. 14:34

    임베디디 기기에 강력하게 특화되어 나온 SQLite에 대한 사용법에 대해 간단하게 설명하고자 한다.

    대부분의 스마트폰 모바일 기기의 경우 Sqlite를 채택하여 사용하고 있다.

    안드로이드에서 기본적인 DB사용법에 대해 설명하자면 너무나 간단하다.

    초보자도 DB의 개념만 갖고 있다면 충분히 사용 할 수 있을 정도이다.

    좀더 깊이 다루려면 역시 쿼리를 잘 짜야 겠지만 기본적인 RawQuery가 아니더라도

    안드로이드에선 기본적인 쿼리들을 제공해 주기에 그 사용법만 알면 된다.

    Insert를 할때는 ContentValues 를 이용해서 자료를 하나씩 넣어 줘도 되고, Raw로 써도 된다.

    속도는  Raw가 더 빠른것으로 알고 있다.

    리턴타입은 Cursor형식이기때문에 Cursor 를 가지고 데이터를 가져 오면 된다. 이게 그 기본 개념이다.

    crate table  // insert  // select 에 대해서 간단한 예제를 통해 알아 볼 것이다.

    DB 강의는 이 예제를 바탕으로 계속 진행하도록 하겠다. 기본적인 CRUD // RAW 쿼리 사용 // GUI툴을 이용한 사용

    응용 쿼리등을 다뤄 보도록 하겠다.

    실행 화면

     



    간단하게 테이블을 생성해서 그 테이블에 데이터를 추가 하면 리스트로 조회 하는 형식의 예제다.

    코드에 짤막한 주석을 넣어 놨으니 코드를 보면서 이해해 주길 바란다.

    DBHelper.java

    package epong.dbsample;
    
    import android.content.*;
    import android.database.sqlite.*;
    
    public class DBHelper extends SQLiteOpenHelper{
    	private static final String DB_NAME = "tb_sample"; 	// 저장될 DB 이름
    	private static final int 	DB_VER = 1;				// DB 버전
    	
    	public DBHelper(Context context) {
    		super(context, DB_NAME, null, DB_VER);
    	}
    	
    	@Override
    	public void onCreate(SQLiteDatabase db) {
    		//테이블 생성 및 초기 작업 
    		String sql = "create table tb_score(" +
    			"code integer primary key autoincrement," +
    			"name text not null, score integer not null)";
    		db.execSQL(sql);  
    	}
    	
    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		//DB의 버전이 바뀌면 수행
    		db.execSQL("drop table if exist tb_score");
    		onCreate(db);
    	}
    }
    

    SQLiteOpenHelper 를 이용해서 테이블을 만들고 버전을 관리 한다.
    이제 쿼리를 담을 클래스를 작성한다.
    DBHandler.java
    package epong.dbsample;
    
    import android.content.*;
    import android.database.*;
    import android.database.sqlite.*;
    
    public class DBHandler {  //DML 선언
    	private Context ctx;
    	private DBHelper helper;
    	private SQLiteDatabase db;
    	
    	public DBHandler(Context ctx) {
    		this.ctx = ctx;
    		helper = new DBHelper(ctx);
    		db = helper.getWritableDatabase(); //DB가 open 됨
    	}
    	
    	public static DBHandler open(Context ctx) throws SQLException{
    		DBHandler handler = new DBHandler(ctx);
    		return handler;
    	}
    	
    	public void close(){
    		helper.close();
    	}
    	
    	//SQL문 작성
    	//INSERT
    	public long insert(String name, String score){
    		ContentValues values = new ContentValues();
    		values.put("name", name);
    		values.put("score", score);
    
    		long result = db.insert("tb_score", null, values);
    		return result;
    	}
    	
    	//SELECT
    	public Cursor selectAll(){
    		Cursor cursor = db.query(true, "tb_score", 
    			new String[]{"code", "name", "score"}, 
    			null, null, null, null, null, null);
    		return cursor;
    	}
    }
    

    앞서 말한대로 ContentValues 를 이용한 데이터 삽입과 Cursor 를 이용한 Select를 보여 준다. return은 커서로
    바로 넘겼지만 보통은 데이터를 바로 저장시켜서 넘기는 편이 Cursor 관리가 더 수월하다.
    마지막으로 사용자가 다루는 클래스
    MainApp.java
    package epong.dbsample;
    
    import android.app.*;
    import android.database.*;
    import android.os.Bundle;
    import android.util.*;
    import android.view.*;
    import android.view.View.*;
    import android.widget.*;
    
    public class MainApp extends ListActivity implements OnClickListener{
        DBHandler dbHandler;
        EditText edtName, edtScore;
        Cursor cursor = null;
        String[] arr = null;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            Button btnIns = (Button)findViewById(R.id.btnIns);
            Button btnResult = (Button)findViewById(R.id.btnResult);
            btnIns.setOnClickListener(this);
            btnResult.setOnClickListener(this);
            
            edtName = (EditText)findViewById(R.id.edtSang);
            edtScore = (EditText)findViewById(R.id.edtScore);
        }
        
        @Override
        public void onClick(View v) {
        	dbHandler = DBHandler.open(this);
        	try {
    			if(v.getId() == R.id.btnIns){  //추가
    				if(edtName.getText().toString().equals("")){
    					Toast.makeText(this, "이름 입력", 2000).show();
    					return;
    				}else if(edtScore.getText().toString().equals("")){
    					Toast.makeText(this, "점수 입력", 2000).show();
    					return;
    				}
    				
    				long re = dbHandler.insert(
    						edtName.getText().toString(), 
    						edtScore.getText().toString());
    				if(re == 0){
    					Toast.makeText(this, "추가 실패", 2000).show();
    				}else{
    					Toast.makeText(this, "추가 성공", 2000).show();
    					cursor = dbHandler.selectAll();
    					arr = new String[cursor.getCount()];
    					int count = 0;
    					while(cursor.moveToNext()){
    						String code = cursor.getString(0);
    						String sang = cursor.getString(1);
    						String price = cursor.getString(2);
    						arr[count] = code + " " + sang + " " + price;
    						count++;
    					}
    					cursor.close();
    					
    					invalidate();
    				}
    			}else if(v.getId() == R.id.btnResult){ //목록보기
    				cursor = dbHandler.selectAll();
    				arr = new String[cursor.getCount()];
    				int count = 0;
    				while(cursor.moveToNext()){
    					String code = cursor.getString(0);
    					String sang = cursor.getString(1);
    					String price = cursor.getString(2);
    					arr[count] = code + " " + sang + " " + price;
    					count++;
    				}
    				cursor.close();
    				
    				invalidate();
    			}
    		} catch (Exception e) {
    			Log.i("disp", "err:" + e);
    		}
        }
        
        private void invalidate(){
        	ListAdapter adapter = new ArrayAdapter(this,
    				android.R.layout.simple_list_item_1, arr);
    		setListAdapter(adapter);
        }
    }
    
    안드로이드 기본 ListView형식으로 진행하였다.
    XML 파일 main.xml
    
    
    
    
    
    	
    	
    
    
    	
    	
    
    
    	

    파일은 첨부해 두겠다. 다음엔 update와 delete에 대해서 구현해 보자.

    댓글

COPYRIGHT 2010 EpoNg. ALL RIGHTS RESERVED.