Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android SQLite에서 ContentValues 없이 SQL 구문으로 데이터 저장하는 방법

Android SQLite에서 ContentValues 없이 SQL 구문으로 데이터 저장하는 방법

본격적인 예제에 앞서, 안드로이드에서 SQLite 데이터베이스가 무엇인지 간단히 짚고 넘어가겠습니다. SQLite는 데이터를 기기 내 텍스트 파일 형태로 저장하는 오픈소스 SQL 데이터베이스입니다. 안드로이드에는 SQLite 데이터베이스 구현이 기본으로 탑재되어 있으며, SQLite는 관계형 데이터베이스가 제공하는 모든 기능을 지원합니다. 또한 JDBC, ODBC처럼 별도의 연결 설정 과정 없이도 데이터베이스에 바로 접근할 수 있다는 점이 큰 장점입니다.

이 예제에서는 안드로이드 SQLite에서 ContentValues 객체를 사용하지 않고 execSQL() 메서드로 SQL 구문을 직접 실행하여 데이터를 저장하는 방법을 단계별로 살펴봅니다.

1단계: Android Studio에서 새 프로젝트 생성

Android Studio를 열고 File ⇒ New Project를 선택한 뒤, 새 프로젝트 생성에 필요한 모든 정보를 입력합니다.

2단계: res/layout/activity_main.xml에 코드 추가

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <EditText
      android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:hint = "Enter Name"
      android:layout_height = "wrap_content" />
   <EditText
      android:id = "@+id/salary"
      android:layout_width = "match_parent"
      android:inputType = "numberDecimal"
      android:hint = "Enter Salary"
      android:layout_height = "wrap_content" />
   <Button
      android:id = "@+id/save"
      android:text = "Save"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
</LinearLayout>

위 레이아웃 코드에는 이름(name)과 급여(salary)를 입력받는 두 개의 EditText와 저장 버튼이 배치되어 있습니다. 사용자가 저장 버튼을 클릭하면 입력한 데이터가 SQLite 데이터베이스에 저장됩니다.

3단계: src/MainActivity.java에 코드 추가

package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   Button save;
   EditText name, salary;
   @Override
   protected void onCreate(Bundle readdInstanceState) {
      super.onCreate(readdInstanceState);
      setContentView(R.layout.activity_main);
      final DatabaseHelper helper = new DatabaseHelper(this);
      name = findViewById(R.id.name);
      salary = findViewById(R.id.salary);
      findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
               if (helper.insert(name.getText().toString(), salary.getText().toString())) {
                  Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
               } else {
                  Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
               }
            } else {
               name.setError("Enter NAME");
               salary.setError("Enter Salary");
            }
         }
      });
   }
}

MainActivity에서는 사용자가 입력한 이름과 급여가 비어 있는지 먼저 검사합니다. 두 값이 모두 입력되어 있으면 DatabaseHelper의 insert() 메서드를 호출하고, 삽입이 성공하면 "Inserted" 토스트 메시지를, 실패하면 "NOT Inserted" 토스트 메시지를 화면에 표시합니다. 입력값이 비어 있으면 해당 EditText에 오류 메시지를 표시해 사용자에게 알려줍니다.

4단계: src/DatabaseHelper.java에 코드 추가

package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DatabaseHelper extends SQLiteOpenHelper {
   public static final String DATABASE_NAME = "salaryDatabase1";
   public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
   public DatabaseHelper(Context context) {
      super(context,DATABASE_NAME,null,1);
   }
   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(
         "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY AUTOINCREMENT, name  text,salary text,CHECK (salary> = 10000) )"
      );
   }
   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
      onCreate(db);
   }
   public boolean insert(String s, String s1) {
      SQLiteDatabase db = this.getWritableDatabase();
      db.execSQL("INSERT INTO "+ CONTACTS_TABLE_NAME +"("+"id,name,salary"+")"+" VALUES "+" ("+"1"+",'"+s+"','"+s1+"')");
      /* ContentValues contentValues = new ContentValues();
      contentValues.put("name", s);
      contentValues.put("salary", s1);
      db.insert(CONTACTS_TABLE_NAME, null, contentValues);*/
      return true;
   }
}

DatabaseHelper 클래스가 이 예제의 핵심입니다. onCreate() 메서드에서는 급여(salary)가 10000 이상인지 검사하는 CHECK 제약 조건이 포함된 테이블을 생성합니다. 그리고 insert() 메서드에서는 주석 처리된 ContentValues 방식 대신, execSQL() 메서드에 "INSERT INTO 테이블명(컬럼...) VALUES(...)" 형태의 SQL 구문을 문자열로 직접 조합해 실행함으로써 ContentValues 없이 데이터를 삽입합니다.

애플리케이션 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 모바일 기기를 선택하면 기기에 기본 화면이 표시됩니다.

Android SQLite에서 ContentValues 없이 SQL 구문으로 데이터 저장하는 방법

아래와 같이 이름과 급여 값을 입력한 뒤 저장 버튼을 클릭합니다.

Android SQLite에서 ContentValues 없이 SQL 구문으로 데이터 저장하는 방법

입력한 데이터가 정상적으로 저장되었는지 확인하려면 Android Studio에서 아래와 같이 데이터베이스를 검사하면 됩니다.

Android SQLite에서 ContentValues 없이 SQL 구문으로 데이터 저장하는 방법