프로그래밍 검색 블로그

안드로이드 SQLite 사용 Create, Index 본문

Android

안드로이드 SQLite 사용 Create, Index

코딩조무사 2018. 2. 12. 00:48

기본적인 안드로이드의 SQLite 사용법과

table 구성, 그리고 인덱스까지 알아본다


일단 테이블 구성은


Bread (name, price)로 만들어보았다

테이블 생성 후 인덱스를 생성하여

대용량 데이터베이스가 들어가도 문제가 없다 



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
package com.example.d.sqliteexample;
 
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

 
import java.util.ArrayList;
import java.util.List;
 
 
public class BreadSqlHelper extends SQLiteOpenHelper{
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Bread";
 
    private static class Bread{
        /**
         * 내부적으로 사용하는 Bread
         */
        String name;
        int price;
 
        Bread(String name, int price) {
            this.name = name;
            this.price = price;
        }
    }
 
    public BreadSqlHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        //빵과 관련한 테이블을 만듭니다
        //아이디,
        //이름,
        //가격으로 구성하였으며 아이디 값은 자동 증가입니다
        db.execSQL("create table if not exists bread (_id integer primary key autoincrement, name text, price integer)");
 
        //이름으로만 가져오는 인덱스를 만듭니다 이름은 고유합니다
        db.execSQL("create unique index if not exists bread_id on bread(name)");
 
        //전체 목록을 가져오는 인덱스를 만듭니다
        db.execSQL("create index if not exists bread_id_name_price on bread(_id, name, price)");
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion < newVersion){
            //업그레이드 할때 하는 작업
            final ArrayList<Bread> tempList = new ArrayList<>();
 
            //1. 기존 데이터 tempList 에 저장
            try(Cursor cursor = db.rawQuery("select name, price from bread"null)){
                String name = cursor.getString(1);
                int price = cursor.getInt(1);
                tempList.add(new Bread(name, price));
            }
 
 
            //기존 db 제거
            db.rawQuery("drop index bread_id"null);
            db.rawQuery("drop index bread_id_name_price"null);
            db.rawQuery("drop table bread"null);
 
            //db 생성 작업 실행
            onCreate(db);
 
 
            //새로운 db 에 추가
            //db 가 변경점이 생겼을 때 하는 작업이므로
            //변경을 거쳐서 아래에 추가할 것.
            //
            //beginTransaction 안에서 insert 를 하게 되면 전반적인 성능이 올라갑니다
            db.beginTransaction();
            try {
                for (Bread b : tempList) {
                    Log.i("BreadSqlHelper", b.name + " " + b.price);
                    //여기에 추가하세요
                    //db.rawQuery("insert into bread.... ")
                }
                db.setTransactionSuccessful();
            }
            finally {
                db.endTransaction();
            }
 
        }
    }
}
 
cs





MainActivity 구성은 사용해본걸 출력하는걸로 만들어보았다 


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
package com.example.d.sqliteexample;
 
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    private BreadSqlHelper breadDb;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textView);
 
        breadDb = new BreadSqlHelper(getApplicationContext());
 
        //반복 테스트를 하고 있으므로 실행시마다 전부 삭제
        breadDb.getWritableDatabase().execSQL("delete from bread");
 
 
        //기본 SQL 로 inset를 합니다
        breadDb.getWritableDatabase().execSQL("insert into bread(name, price) values('소보루빵', 1000)");
 
        ContentValues insertValue = new ContentValues();
        insertValue.put("name""팥빵");
        insertValue.put("price"300);
        breadDb.getWritableDatabase().insert("bread","", insertValue);
 
        //미리 컴파일된 sql 을 만들고 실행합니다
        //실행후 끝내는것이 아니라 close 만 호출하지 않는다면 bind 만 바꿔서 재실행이 가능합니다
        //1부터 시작합니다
        SQLiteStatement statement = breadDb.getWritableDatabase().compileStatement("insert into bread(name, price) values(?, ?)");
        statement.bindString(1"붕어빵");
        statement.bindLong(2200);
        statement.executeInsert();
        statement.close();
 
 
 
        //db의 모든 원소들을 출력합니다
        //놀랍게도 여긴 0부터 시작합니다
        StringBuffer print = new StringBuffer();
        try(Cursor cursor = breadDb.getReadableDatabase().rawQuery("select * from bread"null)){
            while(cursor.moveToNext()){
                print.append(cursor.getString(0))
                        .append(" ")
                        .append(cursor.getString(1))
                        .append(" ")
                        .append(cursor.getString(2))
                        .append("\n");
            }
        }
 
        textView.setText(print.toString());
 
 
    }
}
 
cs




Comments