Home DB 데이터 조회하기
Post
Cancel

DB 데이터 조회하기

데이터 조회하기

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
115
116
117
118
119
120
121
122
123
public class MainActivity extends AppCompatActivity {
    EditText editText;
    EditText editText2;
    TextView textView;

    DatabaseHelper dbHelper;
    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();
            }
        });

        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQuery();
            }
        });
    }


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

        dbHelper = new DatabaseHelper(this);
        database = dbHelper.getWritableDatabase();

        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");
    }

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

        // SQL 실행하고 Cursor 객체 반환하기
        Cursor cursor = database.rawQuery("select _id, name, age, mobile from emp", null);
        int recordCount = cursor.getCount();
        println("레코드 개수 : " + recordCount);

        for (int i = 0; i < recordCount; 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 + ", " + name + ", " + age + ", " + mobile);
        }

        cursor.close();
    }

}

표준 SQL은 데이터를 조회하기 select 구문을 사용하게 되는데 이 구문을 통해 반환되는 Cursor 객체를

받기 위해 rawQuery 메서드를 실행한다.

rawQuery는 결과 값으로 Cursor 객체를 받을 수 있는 SQL 실행 방법이다.

API

1
public Cursor rawQuery (String sql, Sting [] selectionArgs)

Cursor 객체는 결과 테이블에 들어있는 각각의 레코드를 순서대로 접근할 수 있는 방법을 제공한다.

Cursor 객체는 처음에 아무런 레코드를 가르키지 않으며, moveToNext 메서드를 이용해 그 다음 레코드를

가르키도록 해야 레코드 값을 가져올 수 있다.

보통 while 구문을 이용해 moveToNext가 false 값을 반환할 때 까지 레코드 값을 가져오는 방법을 사용한다.

Cursor API

cursor를 사용하고 close 메서드를 이용하여 닫아 줘야 한다.


결과

1


데이터 베이스를 사용할 때 기억해야 할 것

순서내용사용 메서드
1. 데이터베이스 만들기데이터베이스를 만들면 SQLiteDatabase 객체 반환openOrCreateDatabase()
2. 테이블 만들기‘CREATE TABLE …’ SQL을 정의한 후 실행함execSQL()
3. 레코드 추가하기‘INSERT INTO …’ SQL을 정의한 후 실행함execSQL()
4. 데이터 조회하기‘SELECT FROM …’ SQL을 정의한 후 실행함
Cursor 객체가 반환되며 Cursor를 통해
확인한 레코드를 리스트뷰 등에 표시함
rawQuery()
This post is licensed under CC BY 4.0 by the author.