본문 바로가기

나 어제 배웠다/Android

Android SQLite

Android SQLite

 

1. 프로젝트 생성

 

 

2. main.xml widget 추가

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="SQLite Test"
    android:textSize="12pt"
    android:gravity="center"/>
   
 <Button
    android:id="@+id/b01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="테이블생성"/>
 <Button
    android:id="@+id/b02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="테이블삭제"/>
   
 <LinearLayout
    style="@style/ll">  
  <Button
     android:id="@+id/b03"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="입력"
     android:layout_weight="1"/>
  <Button
     android:id="@+id/bselect"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="조회"
     android:layout_weight="1"/>  
  <Button
     android:id="@+id/b04"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="수정"
     android:layout_weight="1"/>
  <Button
     android:id="@+id/b05"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="삭제"
     android:layout_weight="1"/>   
 </LinearLayout>
 
 <LinearLayout
    style="@style/ll">
    <TextView
       style="@style/tv"
       android:text="번호"/>
  <EditText
     android:id="@+id/et01"
     style="@style/et"
     android:hint="ex)자동증가키"/>
 </LinearLayout>
 
 <LinearLayout
    style="@style/ll">
    <TextView
       style="@style/tv"
       android:text="이름"/>
  <EditText
     android:id="@+id/et02"
     style="@style/et"
     android:hint="ex)홍길동"/>
 </LinearLayout>
 
 <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10px">
    <TextView
       style="@style/tv"
       android:text="주소"/>
  <EditText
     android:id="@+id/et03"
     style="@style/et"
     android:hint="ex)서울시"/>
 </LinearLayout> 

</LinearLayout>

※styles.xml을 이용하여 간략하게 처리하기

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <style name="et">
  <item name="android:layout_width">fill_parent</item>
  <item name="android:layout_height">wrap_content</item>
 </style>
 <style name="tv">
  <item name="android:layout_width">wrap_content</item>
  <item name="android:layout_height">wrap_content</item>
  <item name="android:textSize">12pt</item>
 </style>
 <style name="ll">
  <item name="android:layout_width">fill_parent</item>
  <item name="android:layout_height">wrap_content</item>
  <item name="android:orientation">horizontal</item>
  <item name="android:layout_marginTop">10px</item>
 </style>
</resources>

 

3. SqliteDBTestActivity.java Event 추가

 package hjh.data.db;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SqliteDBTestActivity extends Activity implements View.OnTouchListener{
    /** Called when the activity is first created. */
 private Button createB, dropB, insertB, updateB, deleteB, selectB;
 private EditText et1, et2, et3;
 private SQLiteDatabase db;
 private final static String DB_NAME="hjh.db";                        //DB name setting
 private final static int DB_MODE=Context.MODE_PRIVATE;
 private final static String T_NAME="address";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        createB = (Button)findViewById(R.id.b01);
        dropB = (Button)findViewById(R.id.b02);
        insertB = (Button)findViewById(R.id.b03);
        updateB = (Button)findViewById(R.id.b04);
        deleteB = (Button)findViewById(R.id.b05);
        selectB = (Button)findViewById(R.id.bselect);
       
        createB.setOnTouchListener(this);
        dropB.setOnTouchListener(this);
        insertB.setOnTouchListener(this);
        updateB.setOnTouchListener(this);
        deleteB.setOnTouchListener(this);
        selectB.setOnTouchListener(this);
       
        et1 = (EditText)findViewById(R.id.et01);
        et2 = (EditText)findViewById(R.id.et02);
        et3 = (EditText)findViewById(R.id.et03);
       
        openDB();
    }
   
    //DB open
    private void openDB(){
     db = openOrCreateDatabase(DB_NAME, DB_MODE, null);
     showToast("DB("+DB_NAME+")생성 or 열림");
    }
    //Message
    private void showToast(String msg) {
  // TODO Auto-generated method stub
  Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
 }
 @Override
 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
     if(v ==createB){
      createTable();
     }else if(v == dropB){
      dropTable();
     }else if(v == insertB){
      insertData();
     }else if(v == updateB){
      updateData();
     }else if(v == deleteB){
      deleteData();
     }else{ //v == selectB
      selectData();
     }
  return false;
 }
 
 //SQL Process
 private boolean execSQL(String sql){
  try{
   db.execSQL(sql);
   return true;
  }catch (SQLException se) {
   // TODO: handle exception
   return false;
  }  
 }
 
 //Data Select
 private void selectData() {
  // TODO Auto-generated method stub
  String sql = "SELECT _id, name, addr FROM ";
  sql += T_NAME;
  sql += " WHERE _id = ";
  sql += et1.getText().toString();
  Log.e("selectData(): ",sql);
  try{
   Cursor cur = db.rawQuery(sql, null);
   
   cur.moveToFirst();
   if(cur.getCount() > 0){
    et2.setText(cur.getString(1));
    et3.setText(cur.getString(cur.getColumnIndex("addr"))); 
   }else{
    showToast("조회 데이타가 없습니다.");
   }
   
  }catch (SQLException se) {
   // TODO: handle exception
   Log.e("selectData()Error! : ",se.toString());
  }   
 }
 
 //Data Delete
 private void deleteData() {
  // TODO Auto-generated method stub
  String sql = "DELETE FROM ";
  sql += T_NAME;
  sql += " WHERE _id = ";
  sql += et1.getText().toString();
  
  if(!this.execSQL(sql)){
   showToast("Data("+T_NAME+")delete Error!");
  }else{
   showToast("Data("+T_NAME+")delete OK!");
  }
 }
 
 //Data Update
 private void updateData() {
  // TODO Auto-generated method stub
  String sql = "UPDATE ";
  sql += T_NAME;
  sql += " SET ";
  sql += " name = '";
  sql += et2.getText().toString();
  sql += "', addr = '";
  sql += et3.getText().toString();
  sql += "' WHERE _id = ";
  sql += et1.getText().toString();
  
  if(!this.execSQL(sql)){
   showToast("Data("+T_NAME+")update Error!");
  }else{
   showToast("Data("+T_NAME+")update OK!");
  }
 }
 
 //Data Insert
 private void insertData() {
  // TODO Auto-generated method stub
  String sql = "INSERT INTO ";
  sql += T_NAME;
  sql += "(name,addr,ddate) VALUES ( '";
  sql += et2.getText().toString();
  sql += "', '";
  sql += et3.getText().toString();
  sql += "', ";  
  sql += "date('now') )";
  
  if(!this.execSQL(sql)){
   showToast("Data("+T_NAME+")insert Error!");
  }else{
   showToast("Data("+T_NAME+")insert OK!");
  }
 }
 
 //Table Drop
 private void dropTable() {
  // TODO Auto-generated method stub
  String sql = "drop table ";
  sql += T_NAME;
  
  try{
   db.execSQL(sql);
   showToast("Table("+T_NAME+")삭제 완료!");
  }catch (SQLException se) {
   // TODO: handle exception
   Log.e("dropTable()Error! : ",se.toString());
  }
 }
 
 //Table Create
 private void createTable() {
  // TODO Auto-generated method stub
  String sql = "create table ";
  sql += T_NAME;
  sql += "(_id integer primary key autoincrement, name text not null, ";
  sql += "addr text default 'seoul', ddate date)";
  
  try{
   db.execSQL(sql);
   showToast("Table("+T_NAME+")생성 완료!");
  }catch (SQLException se) {
   // TODO: handle exception
   //Log.e("createTable()시오류 : ",se.toString());
  }
 }

}

 

4. 실행결과

 * 프로그램 실행시 DB 생성 or 열림 메세지 확인

 

 * 테이블생성 실행 => Table()생성 완료! 메세지 확인

 * 테이블삭제 => Table()삭제완료! 메세지 확인

 * 다시한번 테이블 생성

 * 이름/주소 입력 후 입력버튼 클릭 => Data()Insert OK! 메세지 확인

 * 번호 : 1 입력 후 조회 버튼 클릭 => 데이타()조회 완료 되었습니다. 메세지 확인

 * 번호1 입력, 이름 변경, 주소 변경 후 수정 버튼 클릭 => Data()Update OK! 메세지확인

 * 번호 1 입력 후 삭제 버튼 클릭 => Data() Delete OK! 메세지 확인

 

 

5. Database 생성 확인

 * 이클립스 오른편 상단 DDMS 클릭

 

 * File Explorer

data > data > hjh.data.db > databases > hjh.db 생성 확인

 * File Explorer가 없으면 추가 => 이클립스 화면 왼편 하단 아이콘 클릭

 * File Explorer 선택

 

6. DB 생성 확인

윈도우 시작 > 실행 > cmd

 

명령어 입력

adb shell

 

이동(4.File Explorer 위치)
# cd data/data/hjh.data.db/databases
cd data/data/hjh.data.db/databases

DB실행

# sqlite3 hjh.db
sqlite3 hjh.db