1. SQLite 프로그래밍

- 안드로이드 앱 개발을 위한 SQLite 동작 방식

SQLiteOpenHelper 클래스를 상속받아 새로운 클래스 생성하여 데이터베이스 파일과 테이블을 생성하는 내용을 코딩

② SQLiteOpenHelper 클래스의 getWritableDatabase()를 사용하여 SQLiteDatabase 클래스를 반환받고, execSQL() 또는 rawQuery() 등으로 SQL문 실행

③ 특히, SELECT문은 Cursor 인터페이스를 반환받은 후에 반복해서 테이블의 행 데이터에 접근

 

- 주로 사용되는 메소드

 

- 예시 (실습: 가수 그룹 관리 DB 앱 만들기)

- 화면 디자인

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="이름: "
            android:textSize="20dp"/>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/edtName"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="인원: "
            android:textSize="20dp"/>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/edtNumber"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnInit"
            android:text="초기화"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnInsert"
            android:text="입력"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnUpdate"
            android:text="수정"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnDelete"
            android:text="삭제"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnSelect"
            android:text="조회"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="8"
        android:orientation="horizontal">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/edtNameResult"
            android:layout_weight="1"
            android:background="#00ff00"
            android:padding="20dp"/>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/edtNumberResult"
            android:layout_weight="1"
            android:background="#00ff00"
            android:padding="20dp"/>

    </LinearLayout>

</LinearLayout>

 

- Java 코드

package com.cookandroid.project12_2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    myDBHelper myHelper;
    EditText edtName, edtNumber, edtNameResult, edtNumberResult;
    Button btnInit, btnInsert, btnSelect, btnUpdate, btnDelete;
    SQLiteDatabase sqlDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("가수 그룹 관리 DB");
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.firefox);

        edtName = (EditText) findViewById(R.id.edtName);
        edtNumber = (EditText) findViewById(R.id.edtNumber);
        edtNameResult = (EditText) findViewById(R.id.edtNameResult);
        edtNumberResult = (EditText) findViewById(R.id.edtNumberResult);
        btnInit = (Button) findViewById(R.id.btnInit);
        btnInsert = (Button) findViewById(R.id.btnInsert);
        btnSelect = (Button) findViewById(R.id.btnSelect);
        btnUpdate = (Button) findViewById(R.id.btnUpdate);
        btnDelete = (Button) findViewById(R.id.btnDelete);

        myHelper = new myDBHelper(this);

        //초기화
        btnInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //groupDB를 쓰기용 데이터베이스로 열기
                sqlDB = myHelper.getWritableDatabase();
                myHelper.onUpgrade(sqlDB, 1, 2);    //1, 2 파라미터는 사용X
                sqlDB.close();
            }
        });

        //입력
        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //쓰기전용 데이터베이스 열기
                sqlDB = myHelper.getWritableDatabase();
                //SQL문 실행
                sqlDB.execSQL("INSERT INTO groupTBL VALUES('"
                        + edtName.getText().toString() + "' , "
                        + edtNumber.getText().toString() + ");");
                sqlDB.close();

                Toast.makeText(getApplicationContext(), "입력됨", Toast.LENGTH_SHORT).show();
                btnSelect.callOnClick();    //바로 btnSelect가 실행됨
            }
        });
        
        
        //수정
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //쓰기용 데이터베이스열기
                sqlDB = myHelper.getWritableDatabase();
                //SQL문 실행
                if(edtName.getText().toString() != "") {
                    sqlDB.execSQL("UPDATE groupTBL SET gNumber ="
                        + edtNumber.getText() + " WHERE gName = '" 
                        + edtName.getText().toString() + "';");
                }
                sqlDB.close();
                
                Toast.makeText(getApplicationContext(), "수정됨", Toast.LENGTH_SHORT).show();                
                btnSelect.callOnClick();    //바로 btnSelect가 실행됨
            }
        });
        
        //삭제
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //읽고 쓰기용 데이터베이스 열기
                sqlDB = myHelper.getWritableDatabase();
                if(edtName.getText().toString() != "") {
                    sqlDB.execSQL("DELETE FROM groupTBL WHERE gName = '"
                            + edtName.getText().toString() + "';");
                }
                sqlDB.close();

                Toast.makeText(getApplicationContext(), "삭제됨", Toast.LENGTH_SHORT).show();
                btnSelect.callOnClick();    //바로 btnSelect가 실행됨                
            }
        });
        
        //조회
        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //읽기전용 데이터베이스 열기
                sqlDB = myHelper.getReadableDatabase();
                //SELECT문을 사용하기 위해 Cursor 이용 -> 반복해서 테이블의 모든 행 데이터에 접근
                Cursor cursor;
                //SELECT문은 rawQuery() 이용
                cursor = sqlDB.rawQuery("SELECT * FROM groupTBL;", null);

                String strNames = "그룹 이름" + "\r\n" + "------------" + "\r\n";
                String strNumbers = "인원" + "\r\n" + "------------" + "\r\n";

                //현재 커서의 다음 행으로 이동 - 행 데이터의 개수만큼 반복됨 - 마지막엔 false로 while문 빠져나감
                while(cursor.moveToNext()) {
                    strNames += cursor.getString(0) + "\r\n";
                    strNumbers += cursor.getString(1) + "\r\n";
                }

                edtNameResult.setText(strNames);
                edtNumberResult.setText(strNumbers);

                cursor.close();
                sqlDB.close();
            }
        });
    }

    //1. QLiteOpenHelper 상속받는 myDBHelper 클래스 생성
    public class myDBHelper extends SQLiteOpenHelper {
        public myDBHelper(Context context) {
            super(context, "groupDB", null, 1);
        }

        //테이블 생성
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE groupTBL (gName CHAR(20) PRIMARY KEY, gNumber INTEGER);");
        }

        //테이블 삭제 후 다시 생성
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS groupTBL");
            onCreate(db);
        }
    }
}

+ Recent posts