본문으로 바로가기

[Android] 앱 - 데이터베이스 연동하기

category Back-end/Android 2016. 6. 20. 13:50

앱에서 쓰는 DB

SQL Lite : 경량화 되어있다. 성능이 많이 빠르지 않다. c로 만들어진 솔루션

문법은 일반 sql과 비슷하다. 

데이터베이스 설치없이 내부에서 쓸 수 있다.


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
package com.ktds.jgbaek.mydatabase;
 
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
import com.ktds.jgbaek.mydatabase.db.DBHelper;
 
public class MainActivity extends AppCompatActivity {
 
    private Button btnCreateDatabase;
    private DBHelper dbHelper;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btnCreateDatabase = (Button) findViewById(R.id.btnCreateDatabase);
        btnCreateDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                final EditText etDBName = new EditText(MainActivity.this);
                etDBName.setHint("DB명을 입력하세요");
 
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("Database 이름을 ")
                        .setMessage(("Database 이름을 입력하세요"))
                        .setView(etDBName)
                        .setPositiveButton("생성"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
 
                                if(etDBName.getText().toString().length()>0){
                                    dbHelper = new DBHelper(MainActivity.this,
                                            etDBName.getText().toString(),
                                            null1);
                                }
                                dbHelper.testDB();
 
                                // Toast.makeText(MainActivity.this, etDBName.getText(), Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("취소"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
 
                            }
                        })
                        .create()
                        .show();
 
            }
        });
    }
}
cs


생성을 누르면 dbHelper에서 새로운 DB가 생성되도록 하였다.


DBHelper



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
package com.ktds.jgbaek.mydatabase.db;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
 
/**
 * Created by 206-006 on 2016-06-20.
 */
public class DBHelper extends SQLiteOpenHelper {
 
    private Context context;
 
 
    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }
 
    /**
     * DB가 존재하지 않을 때, 딱 한번 실행된다
     * DB를 생성하는 역할
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
 
        StringBuffer sb = new StringBuffer();
        sb.append( " CREATE TABLE TEST_TABLE ( ");
        sb.append( " _ID INTEGER PRIMARY KEY AUTOINCREMENT, ");
        sb.append( " NAME TEXT, " );
        sb.append( " AGE INTEGER, ");
        sb.append( " PHONE TEXT); ");
        // SQL 실행
        db.execSQL(sb.toString());
 
        Toast.makeText(context, "테이블 생성됨", Toast.LENGTH_SHORT).show();
    }
 
    /**
     * Application의 버전이 올라가 Table 구조가 변경되었을 때 실행
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Toast.makeText(context, "Version 올라감", Toast.LENGTH_SHORT).show();
    }
 
    public void testDB(){
        SQLiteDatabase db = getReadableDatabase();
    }
}
cs


onCreate절에서 스트링 버퍼를 이용해 새로운 db를 만들어준다.

Main에서 testDB메소드를 호출해 줌으로써 다시 db를 얻어준다.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ktds.jgbaek.mydatabase.MainActivity">

<Button
android:id="@+id/btnCreateDatabase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DB생성" />
</RelativeLayout>