티스토리 뷰


안드로이드는 임베디드 데이터베이스로 개발된 SQLite를 가지고 있다. 이는 표준 SQL을 지원하여 기존에 사용하던 SQL을 그대로 사용할 수 있다는 매우 큰 장점을 가지고 있다. 

 

우선 데이터베이스를 구성하려면 Context 객체가 제공하는 

 

public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)

public abstract boolean deleteDatabase(String name)

메서드를 호출하여 생성, 혹은 삭제할 수 있다.

 

이 때, openOrCreateDatabase의 3번째 파라미터는 null이 아닌 객체를 지정할 경우, 쿼리의 결과 값으로 반환되는 데이터를 참조하는 커서를 만들어낼 수 있는 객체가 전달된다.

 

또한 SQLiteDatabase 객체에서 가장 중요한 메서드 중 하나는 execSQL() 이며, SQL 문을 실행하기 위해 사용한다.

 

public void execSQL(String sql) throws SQLException

 

바로 예제를 확인해보자.


우선 아래와 같이 레이아웃을 구성해준다.

 

◎activity_main.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" android:orientation="vertical">
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:ems="10"
                android:id="@+id/editTextText1" android:layout_weight="1"/>
        <Button
                android:text="Button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/button" android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:ems="10"
                android:id="@+id/editTextText2" android:layout_weight="1"/>
        <Button
                android:text="Button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/button2" android:layout_weight="1"/>
    </LinearLayout>
    <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
                      android:orientation="vertical">
            <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" android:id="@+id/textView"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

 

◎MainActivity

package com.example.simpledatabase;

import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

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.editTextText1);
        editText2 = findViewById(R.id.editTextText2);
        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) {
        textView.append("createDatabase 호출됨.");
        database = openOrCreateDatabase(name, MODE_PRIVATE, null);
        textView.append("데이터베이스 생성함: " + name);
    }

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

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

        database.execSQL("CREATE TABLE IF NOT EXISTS " + name + "(" +
                " _id INTEGER PRIMARY KEY autoincrement," +
                " name TEXT," +
                " age INTEGER," +
                " mobile TEXT" +
                ")");
        textView.append("테이블 생성함: " + name);
    }

    private void insertRecord() {
        textView.append("insertRecord 호출됨.");
        if(database == null) {
            textView.append("데이터베이스를 먼저 생성하세요");
            return;
        }

        if(tableName == null) {
            textView.append("테이블을 먼저 생성하세요.");
            return;
        }
        database.execSQL("INSERT INTO " + tableName +
                "(name, age, mobile)" +
                "VALUES " +
                "('John', 20, '010-1111-1111')"
                );
        textView.append("레코드 추가함.");
    }
}

Comments