SQLite 사용법

android 2020. 2. 5. 11:35

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;
    EditText editText2;
    TextView textView;

    SQLiteDatabase database;

    @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) {
                String tableName = editText2.getText().toString();
                createTable(tableName);
            }
        });

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

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

    public void createDatabase(String databaseName) {
        println("createDatabase 호출됨");

        try {
            database = openOrCreateDatabase(databaseName + ".db", MODE_PRIVATE, null);
            println("데이터베이스 생성됨 : " + databaseName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createTable(String tableName) {
        println("createTable 호출됨");

        try {
            if (database == null) {
                println("데이터베이스를 먼저 열어주세요.");
                return;
            }

            String sql = "create table if not exists " + tableName + "(_id integer PRIMARY KEY autoincrement, name text, age integer, mobile text)";
            database.execSQL(sql);
            println("테이블 생성됨 : " + tableName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertRecord() {
        println("insertRecord 호출됨");

        try {
            if (database == null) {
                println("데이터베이스를 먼저 열어주세요.");
                return;
            }

            String tableName = editText2.getText().toString();
            if (tableName == null) {
                println("테이블 이름을 입력하세요.");
                return;
            }

            String sql = "insert into " + tableName + "(name, age, mobile) values ('홍길동', '20', '010-1000-1000')";
            database.execSQL(sql);
            println("레코드 추가함");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void excuteQuery() {
        println("excuteQuery 호출됨");

        if (database == null) {
            println("테이터베이스를 먼저 열어주세요.");
        }

        String tableName = editText2.getText().toString();
        if (tableName == null) {
            println("테이블 이름을 입력하세요.");
        }

        try {
            String sql = "select _id, name, age, mobile from " + tableName;
            Cursor cursor = database.rawQuery(sql, null);

            int i = 1;
            while (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);
                i++;
            }

            cursor.close();
        } catch (Exception e ) {
            e.printStackTrace();
        }
    }

    public void println(String data) {
        textView.append(data + "\n");
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="데이터베이스 만들기" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="테이블 만들기" />
    </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:layout_weight="1"
            android:text="레코드 추가" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="레코드 조회" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

* SQLite 다운로드

https://sqlitebrowser.org/dl/

'android' 카테고리의 다른 글

연락처 가져오기  (0) 2020.02.05
갤러리 이미지 가져오기  (0) 2020.02.05
gson 사용법  (0) 2020.02.04
Volley 사용법  (0) 2020.02.04
HttpURLConnection 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,