카테고리 없음

안드로이드 스튜디오에서 테이터베이스와 테이블 만들기

백수를 탈출하자 2023. 4. 2. 16:38

activity_main.xml

<?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="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

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

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

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="데이터베이스 만들기" />
    </LinearLayout>

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

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

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

최상위 레이아웃인 constraintlayout을 LinearLayout으로 변경하고 orientation  속성값을 vertical로 설정합니다.기존에 있던 텍스트뷰는 삭제를 하고 첫 출에는 입력상자와 버튼 하나를  LinearLayout에 넣습니다.두 번쨰 줄에도 첫 번쨰 줄과 동일하게 입력상자와 버튼을 배치합니다. 그 아래쪽에 있는 스크롤뷰를 추가하고 그 안에 있는 텍스트뷰 하나가 들어가도록 배치합니다. 첫 번쨰 버튼에는 '데이터베이스 만들기'라는 글자가 표시되도록 하고 두 번째 버튼에는 '테이블 만들기'라는 글자가 표시되도록 text속성을 변경합니다.

MainActivity.java

package org.techtown.database;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    EditText editText2;
    TextView textView;

    SQLiteDatabase database;

    String tableName;

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

        editText = findViewById(R.id.editText);
        editText2 = findViewById(R.id.editText2);
        textView = findViewById(R.id.textView);

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

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

                insertRecord();
            }
        });
    }


    private void createDatabase(String name) {
        println("createDatabase 호출됨.");

        database = openOrCreateDatabase(name, MODE_PRIVATE, null);

        println("데이터베이스 생성함 : " + name);
    }

    private void createTable(String name) {
        println("createTable 호출됨.");

        if (database == null) {
            println("데이터베이스를 먼저 생성하세요.");
            return;
        }

        database.execSQL("create table if not exists " + name + "("
                + " _id integer PRIMARY KEY autoincrement, "
                + " name text, "
                + " age integer, "
                + " mobile text)");

        println("테이블 생성함 : " + name);
    }

    private void insertRecord() {
        println("insertRecord 호출됨.");

        if (database == null) {
            println("데이터베이스를 먼저 생성하세요.");
            return;
        }

        if (tableName == null) {
            println("테이블을 먼저 생성하세요.");
            return;
        }

        database.execSQL("insert into " + tableName
                + "(name, age, mobile) "
                + " values "
                + "('John', 20, '010-1000-1000')");

        println("레코드 추가함.");
    }

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

}

[데이터베이스 만들기]버튼을 눌렀을 떄  호출되는 createDatabase 메서드는 데이터베이스 이름(name)을 전달 받아 openOrCreateDatabase 메서드를 호출합니다.테이블을 만들기 위해서 [테이블 마들기] 버튼을 누르면 createTable메서드를 먼저 호출해 테이블을 만들고 insertRecord메서드를 호출하여 임의의 레코드를 삽입합니다.createTable메서드에서 호출하는 execSQL메서드는 SQL문을 파라미터로 전달받기 떄문에 원하는 기능의 SQL을 먼저 정의해야 합니다.만약 직원 테이블을 만들기 위해 칼럼을 직원 id,이름,나이,휴대폰 번호로 정의하였습니다.id의 경우에는 안드로이드 앞에서' _ '를 붙여'_id' 로 만드는 방법을 권장하므로 같은 이름을 사용하였으며,자동으로 1씩 증가하는 키 값(PRIMARY KEY autoincrement)으로 정의하였습니다.이름,나이,휴대폰 번호는 가각 name.age.mobile칼럼으로 정의하고 그 데이터 타입은text,integer,text가 되도록 하였습니다,insertRecord 메서드에서는 execSQL메서드로 임의의 데이터 John,20,010-1000-1000을 삽입합니다

데이터베이스와 테이블 생성한 결과