본문 바로가기
안드로이드

[Android] 6. 데이터베이스 - 데이터 추가하고 조회하기

qbang 2019. 8. 10.

이번 시간에는 6강 데이터베이스의 두번째 강의인 '데이터베이스 이해하기데이터 추가하고 조회하기' 리뷰입니다.

개념을 알아보면서 실습한 내용을 덧붙여 알아보도록 하겠습니다!

 


데이터베이스와 테이블을 만ㄷ르었다면 테이블에 있는 데이터를 저장하거나 조회할 수 있는데요,

데이터를 조회하는 데 사용되는 SELECT 문은 다양하게 사용됩니다.

 

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">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1. DB 오픈" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="customer.db" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="2. 테이블만들기" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="customer" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3. 데이터 추가하기" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textPersonName"
            android:text="소녀시대" />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textPersonName"
            android:text="20" />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="numberDecimal"
            android:text="010-0000-0000" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4. 데이터 조회하기" />


    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#FFEB3B">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#FFEB3B"
                android:textSize="24dp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

 

MainActivity.java

package com.example.mydb;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedInputStream;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    EditText editText2;
    EditText editText3;
    EditText editText4;
    EditText editText5;

    TextView textView;

    SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);
        editText4 = (EditText) findViewById(R.id.editText4);
        editText5 = (EditText) findViewById(R.id.editText5);

        textView = (TextView) findViewById(R.id.textView2);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String databaseName = editText.getText().toString();
                openDatabase(databaseName);
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String tableName = editText2.getText().toString();
                createTable(tableName);
            }
        });

        Button button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String name = editText3.getText().toString().trim();
                String ageStr = editText4.getText().toString().trim();
                String mobile = editText5.getText().toString().trim();

                int age = -1;
                try{
                    age =  Integer.parseInt(ageStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
                insertData(name, age, mobile);
            }
        });

        Button button4 = (Button) findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String tableName = editText2.getText().toString();
                selectData(tableName);
            }
        });
    }

    public void openDatabase(String databaseName){
        println("openDatabase() 호출됨");

        //DB 저장소 만듦
        database = openOrCreateDatabase(databaseName, MODE_PRIVATE, null);

        //DB가 제대로 생성되었는지 확인
        if(database != null){
            println("데이터베이스 오픈됨");
        }
    }

    public void createTable(String tableName){
        println("createTable() 호출됨");

        if(database != null){
            String sql = "create table " + tableName + "(_id integer PRIMARY KEY autoincrement, name text, age integer, mobile text)";

            //결과 값을 받지 않아도 되는 SQL 문이 있으면 실행
            database.execSQL(sql);

            println("테이블 생성됨");
        }else{
            println("먼저 데이터베이스를 오픈하세요");
        }
    }

    public void println(String data){
        textView.append(data + "\n");
    }

    public void insertData(String name, int age, String mobile){
        println("insertData()");
        if(database != null){
            String sql = "insert into customer(name, age, mobile) values(?,?,?)";
            Object[] params = {name, age, mobile};

            database.execSQL(sql, params);

            println("데이터 추가함함");
       }else{
            println("먼저 데이터베이스를 오픈하세요");
        }

    }

    public void selectData(String tableName){
        println("selectData() 호출됨");

        if(database != null){
            // 데이터 조회
            String sql = "select name, age, mobile from " + tableName;

            //rawQuery 메소드를 호출했을 때 반환되는 객체는 Cursor
            //Cursor 객체는 각각의 레코드를 moveToNext 메소드로 넘겨볼 수 있도록 함
            Cursor cursor = database.rawQuery(sql, null);
            println("조회된 데이터 개수: " + cursor.getCount());

            for(int i = 0; i < cursor.getCount(); i++){
                cursor.moveToNext();
                String name = cursor.getString(0);
                int age = cursor.getInt(1);
                String mobile = cursor.getString(2);

                println("#" + i + " -> " + name + ", " + age + ", " + mobile);
            }

            cursor.close();
        }
    }
}

코드에 대한 설명은 주석으로 달아놨으니 천천히 읽어보시면 될 것 같습니다.

위 코드에 대한 결과 화면은 아래와 같습니다.

 

결과 화면

먼저 데이터베이스를 오픈하고 테이블을 만든 뒤 데이터를 조회하니 조회된 데이터 개수가 0이라고 뜨네요.

데이터 추가하기를 통해 데이터를 넣고 데이터 조회를 하니 조회된 데이터 개수가 증가한 것과 소녀시대, 20, 휴대폰 번호가 들어간 것을 확인할 수 있습니다. 

 

글 읽어주셔서 감사합니다 :)

댓글