Android - 데이터 조회하기

유의선·2023년 9월 13일
0

데이터를 조회하기 위해 사용되는 표준 SQL은 "select ..." 구문을 사용하게 되는데 이 구문을 통해 Cursor 객체를 반환받기 위해 rawQuery 메소드를 실행한다.

즉 결과 값이 없는 SQL의 실행에는 executeSQL 메소드를 사용하고, 결과 값을 Cursor 객체로 받기 위해선 rawQuery 메소드를 사용한다.


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

Cursor 객에는 처음에는 아무런 레코드를 가리지키 않으며, moveToNext 메소드를 이용해 다음 레코드를 가리키도록 해야 레코드 값을 가져올 수 있다.

getCount 메소드를 이용하면 전체 레코드의 개수를 알 수 있다.

이외에 Cursor에 정의된 메소드들은 다음과 같다.

public abstract int getColumnCount()
public abstract int getColumnIndex(String columnName)
public abstract String getColumnName(int columnIndex)
public abstract String[] getColumnNames()

public abstract int getCount()
public abstract boolean moveToNext()
public abstract boolean moveToPrevious()
public abstract boolean moveToFirst()
public abstract boolean moveToLast()
public abstract boolean move(int offset)

public abstract String getString(int columnIndex)
public abstract Short getShort(int columnIndex)
public abstract int getInt(int columnIndex)
public abstract long getLong(int columnIndex)
public abstract float getFloat(int columnIndex)
public abstract double getDouble(int columnIndex)
public abstract byte[] getBlob(int columnIndex)

커서는 데이터베이스와 마찬가지로 사용한 후에는 close 메소드를 이용해 닫아야 한다.


데이터 조회하기

프로젝트는 데이터베이스와 테이블 만들기에서 사용한 프로젝트에서 이어서 진행하였다.

activity_main.xml 파일에 데이터 조회하기 버튼을 추가했다.


MainActivity.java 파일에 '데이터 조회하기' 버튼을 눌렀을 때 데이터를 조회하는 코드를 추가했다.

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

...

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

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

0개의 댓글