0. 출처

https://www.edwith.org/boostcourse-android/lecture/17119/

https://www.edwith.org/boostcourse-android/lecture/17120/



1. 실행 결과 화면

  



2. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.tistory.qlyh8.practice.MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DB Open"/>
        <EditText
            android:id="@+id/edit_text1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            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:text="테이블 생성"/>
        <EditText
            android:id="@+id/edit_text2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            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:text="데이터 추가"/>
        <EditText
            android:id="@+id/edit_text3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Tom"/>
        <EditText
            android:id="@+id/edit_text4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number"
            android:text="20"/>
        <EditText
            android:id="@+id/edit_text5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            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="match_parent"
            android:layout_height="wrap_content"
            android:text="데이터 조회"/>
    </LinearLayout>
 
    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_blue_light"
        android:padding="10dp">
        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"/>
    </ScrollView>
 
</LinearLayout>
 
cs



3. MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.tistory.qlyh8.practice;
 
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
/*
* SQLite 는 오픈소스로, 데이터베이스가 앱에서 하나의 파일로 생성되는 파일 기반의 데이터베이스이다.
* 용량이 적고 가볍게 동작하면서도 관계형 데이터베이스를 위한 SQL 실행이 가능하다.
* PC 에서도 사용할 수 있고, 화면에서 테이블 구조나 데이터를 확인할 수 있는 도구들이 제공된다.
* */
public class MainActivity extends AppCompatActivity {
    EditText editText1, editText2, editText3, editText4, editText5;
    TextView textView;
    SQLiteDatabase database;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText1 = findViewById(R.id.edit_text1);
        editText2 = findViewById(R.id.edit_text2);
        editText3 = findViewById(R.id.edit_text3);
        editText4 = findViewById(R.id.edit_text4);
        editText5 = findViewById(R.id.edit_text5);
        textView = findViewById(R.id.text_view);
 
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.append("DB OPEN 버튼 클릭함\n");
                String dbName = editText1.getText().toString().trim();
                // openOrCreateDatabase 메소드를 사용하여 데이터베이스를 만들거나 연다.
                // SQLiteDatabase 객체가 반환되며 이 객체를 통해 SQL 을 실행할 수 있다.
                database = openOrCreateDatabase(dbName, MODE_PRIVATE, null);
                if(database != null)
                    textView.append("DB 오픈됨\n");
            }
        });
 
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.append("테이블 추가 버튼 클릭함\n");
                String tableName = editText2.getText().toString().trim();
                if(database != null){
                    String sql = "CREATE TABLE IF NOT EXISTS " + tableName
                            + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phone TEXT)";
                    database.execSQL(sql);
                    textView.append("테이블 생성됨\n");
                } else {
                    textView.append("먼저 데이터베이스를 오픈하세요.\n");
                }
            }
        });
 
        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.append("데이터 추가 버튼 클릭함\n");
                String userName = editText3.getText().toString().trim();
                int userAge = -1;
                String userPhone = editText5.getText().toString().trim();
                try {
                    userAge = Integer.parseInt(editText4.getText().toString().trim());
                } catch (Exception e){
                    e.printStackTrace();
                }
 
                if(database != null){
                    String sql = "INSERT INTO CUSTOMER(name, age, phone) VALUES(?, ?, ?)";
                    Object[] params = {userName, userAge, userPhone};
                    database.execSQL(sql, params);
                    textView.append("데이터 추가됨\n");
                } else {
                    textView.append("먼저 데이터베이스를 오픈하세요.\n");
                }
            }
        });
 
        findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.append("데이터 조회 버튼 클릭함\n");
                String tableName = editText2.getText().toString().trim();
 
                if(database != null){
                    String sql = "SELECT name, age, phone FROM " + tableName;
                    Cursor cursor = database.rawQuery(sql, null);
                    textView.append("데이터 개수: "+ cursor.getCount() + "\n");
 
                    // Cursor 객체를 이용하여 각각의 레코드를 moveToNext 메소드로 넘겨보며
                    // 그 안에 들어있는 칼럼 데이터는 getString, getInt 등의 메소드로 확인한다.
                    for(int i=; i<cursor.getCount() ; i++){
                        cursor.moveToNext();
                        textView.append("#"+(i+1+ ": "
                                + cursor.getString(0+ ", "
                                + cursor.getInt(1+ ", "
                                + cursor.getString(2)
                                + "\n");
                    }
                    cursor.close();
                } else {
                    textView.append("먼저 데이터베이스를 오픈하세요.\n");
                }
            }
        });
    }
}
cs



4. 참고

- SQLite Documentation

https://www.sqlite.org/docs.html


- SQLite Datatypes

https://www.tutorialspoint.com/sqlite/sqlite_data_types.htm


- Save data using SQLite

https://developer.android.com/training/data-storage/sqlite


- Save data in a local database using Room

https://developer.android.com/training/data-storage/room/?hl=ko



+ Recent posts