Android/Android Studio

[Android Studio] SQL database 만들기, create, insert, select

MK_____ 2021. 11. 11. 00:21
package com.example.database;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
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;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    EditText editText2;
    TextView textView;

    //database 객체
    SQLiteDatabase database;

    @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);

        //database 객체생성하기 위한 버튼 클릭
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String databaseName = editText.getText().toString();
                createDatabase(databaseName);
            }
        });

        //table 생성릭하기 위한 버튼 클릭
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tableName = editText2.getText().toString();
                createTable(tableName);
            }
        });

        //컬럼 한줄 추가 (INSERT) 위한 버튼 클릭
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertRecord();
            }
        });

        //SELECT
        Button button4 = findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                executeQuery();
            }
        });



    }

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

        try {
            //database 객체를 만드는 함수
            database = openOrCreateDatabase(databaseName, MODE_PRIVATE, null);
            println("데이터베이스 생성됨" + databaseName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

        if ( database == null ){
            println("데이터베이스를 열어주세요");
            return;
        }

        String sql = "CREATE TABLE " + tableName + "(_id integer PRIMARY KEY autoincrement, name text, age integer, mobile text)";
        database.execSQL(sql);
        println("테이블 생성 됨, 이름 : " + tableName);
    }

    public void insertRecord(){
        println("insertRecord() 호출");

        if ( database == null ){
            println("데이터베이스를 열어주세요");
            return;
        }

        String tableName = editText2.getText().toString();
        if (tableName == null){
            println("테이블 이름을 넣어주세요");
            return;
        }

        String sql = "INSERT INTO " + tableName + " (name, age, mobile) values ('용미경', 30, '010-3923-9995')";
        database.execSQL(sql);
        println("레코드 추가함");
    }

    public void executeQuery(){
        println("executeQuery 호출됨");

        String tableName = editText2.getText().toString();
        if (tableName == null){
            println("테이블 이름을 입력하시오");
        }
        String sql = "SELECT _id, name, age, mobile from " + tableName;
       Cursor cursor = database.rawQuery(sql, null);
       int recordCnt = cursor.getCount();
       println("레코드 갯수 : " + recordCnt);

       for (int i = 0; i < recordCnt; i++ ){
           cursor.moveToNext();

           int id = cursor.getInt(0); // 첫번쨰 컬럼 값 (고유 번호로 지정해줬음)
           String name = cursor.getString(1);
           int age = cursor.getInt(2);
           String mobile = cursor.getString(3);

           println("레코드 #" + i + " : id=> " + id +" name=> " + name + " age=> "+ age +" mobile=> " +mobile);
       }

       cursor.close();// 한정된 자원이라 닫아줘야 함

    }

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