Backend/SQLite

[SQLite] DB 입력, 조회 및 초기화 (예제)

Emil :) 2019. 12. 13. 17:07
728x90
반응형

개요


멀티메모 할일기능, 스와이프 제거 기능들을 추가하려다 보니 기존의 DB와 병합이 어려워서 다시 공부하고자 한다.

 

오늘의 주제


가수 그룹의 이름과 인원을 데이터베이스에 입력하고 조회하는 응용 프로그램을 작성해보자.

 

진행 과정


1. 레이아웃 짜주기

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="이름 : "
            android:textSize="20dp"/>
        <EditText
            android:id="@+id/edtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="인원 : "
            android:textSize="20dp"/>
        <EditText
            android:id="@+id/edtNumber"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

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

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

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical">

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

2. MainActivity.java 짜주기

과정은 주석으로 짜놓았다.

package com.example.a1_dbbasic;

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;

import static java.sql.Types.CHAR;

public class MainActivity extends AppCompatActivity {

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


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

        //xml버튼들 객체연결
        edtName = findViewById(R.id.edtName);
        edtNumber = findViewById(R.id.edtNumber);
        edtNameResult = findViewById(R.id.edtNameResult);
        edtNumberResult = findViewById(R.id.edtNumberResult);
        btnInit = findViewById(R.id.btnInit);
        btnInsert = findViewById(R.id.btnInsert);
        btnSelect = findViewById(R.id.btnSelect);

        //내 DB클래스 객체생성
        myHelper = new myDBHelper(this);

        //각 버튼에 리스너를 달아주자.
        btnInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //groupDB를 쓰기용 DB로 열고, groupTBL이 있으면 삭제한 후 새로 생성한다.
                sqlDB = myHelper.getWritableDatabase();
                myHelper.onUpgrade(sqlDB, 1, 2);
                sqlDB.close();
            }
        });

        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //마찬가지로 쓰기용으로 열고, 쿼리문을 입력해준다. 따옴표에 주의하자.
                sqlDB = myHelper.getWritableDatabase();
                sqlDB.execSQL("INSERT INTO groupTBL VALUES (" +
                        "'" + edtName.getText().toString() + "' ,"
                        + edtNumber.getText().toString() + ");");
                sqlDB.close();
                Toast.makeText(getApplicationContext(), "입력됨", Toast.LENGTH_SHORT).show();
            }
        });

        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //커서를 선언하고 모든 테이블을 조회한 후 커서에 대입한다.
                //이 과정이 조금 이해가 어려운데, 이 커서 객체가 포인터 역할을 한다고 이해하면 된다.
                sqlDB = myHelper.getReadableDatabase();
                Cursor cursor;
                cursor = sqlDB.rawQuery("SELECT * FROM groupTBL;", null);

                //그룹이름과 인원을 나타내 줄 문자열 선언
                String strNames = "그룹 이름" + "\r\n" + "-------" + "\r\n";
                String strNumbers = "인원" + "\r\n" + "-------" + "\r\n";

                
                //커서가 움직이면서  현재 커서의 열 번호 데이터값을 반환해서 문자열 변수에 계속 누적한다.
                //0은 0번째열(그룹이름) , 1은 1번째열(인원)이 된다.
                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();
            }
        });
    }

    //DB를 생성하고 초기화하는 DB생성자 정의
    public class myDBHelper extends SQLiteOpenHelper{
        public myDBHelper(Context context){
            super(context, "groupDB", null, 1);
        }
        @Override
        public void onCreate(SQLiteDatabase db){
            //groupTBL이라는 테이블이름으로 gName, gNumber 필드를 생성해주자
            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);
        }
    }
}

 

 

결과


이제 이걸 토대로 기존에 있던 멀티메모와 합병하고자 한다. (갑자기 생긴 애들은 움짤 촬영 전에 테스트로 생성해놓은애들임)

 

728x90
반응형

'Backend > SQLite' 카테고리의 다른 글

[SQLite] DB Browser for SQLite 사용방법  (0) 2019.12.13