안드로이드 프로그래밍[JAVA Code]/DataBase

SQLite : Database 강좌

훈츠 2019. 12. 17. 22:13
반응형

안드로이드에서는 Sharedpreference 말고, SQLite가 내장되어있어 간단하게 데이터베이스를 구성하여 저장하고 쉽게 조회 할수가 있습니다. 여기서 모바일 데이트 베이스를 만들고, 그안에 테이블을 만들어 저장하고, 조회하는 기능에 대해 설명 하겠습니다. 데이터베이스를 검색해보니, 현재 안드로이드에 내장되어있는 SQLite 말고도 아주 많은 데이터베이스 프로그램이 있었습니다. 하지만 안드로이드에서 데이터베이스 구성하는 방법들에 대해서만 기술해 보도록 하겠습니다. 

1) 데이터 베이스 만들기 : database = openOrCreateDatabase( name, MODE_PRIVATE, null );

public void createDatabase(String name){
        println( "createDatabase 호출 됨" );
        try {
            println( "database 이름을 입력하시오" );
            database = openOrCreateDatabase( name, MODE_PRIVATE, null );
        } catch (SQLException e){
            println(" 에러 발생됨 "+ e.getMessage());
        }
        println( "database 생성함 " + name );
    }

2) 테이블 만들고 그안에 컬럼 정보 넣기 String sql ="create table " 후에 한칸 띄우는것을 유의하세요.

public void createTable(String name){
println( "create Table 호출 됨" );
if (database != null){
	String sql ="create table " 
    			+ name + 
                "(_id integer PRIMARY KEY autoincrement, 
					name text, 
                    age text)";
	try {
	database.execSQL( sql );
	println( "table 생성됨" + name );
	} catch (SQLException e){
	println(" 에러 발생됨 "+ e.getMessage());
	}
	} else {
	println( "database db를 생성 하시오" );
return ;
}
}

3) 데이터 넣기  : "insert into " 띄어쓰기 유의하세요. tableName 뒤에 나오는 "(name, age)" 이부분이 어떤 컬럼을 이용할것인지 넣는 부분.

public void insertInfo(String tableName, String name, String age){
        if(database != null) {
            String sql = "insert into " + tableName + "(name, age) " + "values(?,?)";
            Object[] params = {name, age};
            database.execSQL( sql, params );
            println( "데이터 추가함."+ name +" : " + age  );
        } else {
            println( "먼저 데이터베이스를 오픈하세요" );
        }
    }

4) 데이터 조회화기 : 

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

String sql = "select _id, name, age from " + tableName; //select 구문
Cursor cursor = database.rawQuery(sql, null);//cursor 객체 받기

println("레코드 개수" + cursor.getCount());

for(int i=0; i < cursor.getCount(); i++){
cursor.moveToNext();	
int id = cursor.getInt(0);
String name = cursor.getString(1);
String age = cursor.getString(2);
println("레코드#" + i + "id : "+ id +" : " + name + " , " + age);
}
cursor.close(); //항상 닫아줘야 한다. 
}

5) 전체 코드 1 : XML

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

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

        <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"
            android:text="db" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="테이블 만들기" />

        <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"
            android:text="tt" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="데이터 추가하기" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textPersonName"
            android:text="name" />
        <EditText
            android:id="@+id/editText4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textPersonName"
            android:text="age" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            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="match_parent"
                android:textSize="20dp" />
        </LinearLayout>
    </ScrollView>


</LinearLayout>

6) 전체 코드 2 : JAVA

public class MainActivity extends AppCompatActivity {
    Button button, button2,button3,button4,button5,button6;
    EditText editText,editText2,editText3,editText4,editText5,editText6;
    TextView textView;
    SQLiteDatabase database;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        userfindId();
        userfuction();


    }
    private void  userfindId(){
        button = (Button) findViewById( R.id.button );
        button2 = (Button) findViewById( R.id.button2 );
        button3 = (Button) findViewById( R.id.button3 );
        button4 = (Button) findViewById( R.id.button4 );
        /*
        button5 = (Button) findViewById( R.id.button5 );
        button6 = (Button) findViewById( R.id.button6 );
        */
        editText = (EditText) findViewById( R.id.editText );
        editText2 = (EditText) findViewById( R.id.editText2 );
        editText3 = (EditText) findViewById( R.id.editText3 );
        editText4 = (EditText) findViewById( R.id.editText4 );
        textView = (TextView) findViewById( R.id.textView );
    }
    private void  userfuction(){
        //open or create database
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String databaseName = editText.getText().toString().trim();
                createDatabase( databaseName );
            }
        } );
        //create table
        button2.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tableName = editText2.getText().toString().trim();
                createTable( tableName );
            }
        } );
        //insert data info
        button3.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tableName = editText2.getText().toString().trim();
                String name = editText3.getText().toString().trim();
                String age = editText4.getText().toString().trim();
                insertInfo( tableName, name, age );
            }
        } );
        //select data
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tableName = editText2.getText().toString().trim();
                executeQuery(tableName);
            }
        });
    }
    public void createDatabase(String name){
        println( "createDatabase 호출 됨" );
        try {
            println( "database 이름을 입력하시오" );
            database = openOrCreateDatabase( name, MODE_PRIVATE, null );
        } catch (SQLException e){
            println(" 에러 발생됨 "+ e.getMessage());
        }
        println( "database 생성함 " + name );
    }
    public void createTable(String name){
        println( "create Table 호출 됨" );
        if (database != null){
            String sql ="create table " + name +"(_id integer PRIMARY KEY autoincrement, name text, age text)";
            try {
                database.execSQL( sql );
                println( "table 생성됨" + name );
            } catch (SQLException e){
                println(" 에러 발생됨 "+ e.getMessage());
            }
        } else {
            println( "database db를 생성 하시오" );
            return ;
        }
    }
    public void insertInfo(String tableName, String name, String age){
        if(database != null) {
            String sql = "insert into " + tableName + "(name, age) " + "values(?,?)";
            Object[] params = {name, age};
            database.execSQL( sql, params );
            println( "데이터 추가함."+ name +" : " + age  );
        } else {
            println( "먼저 데이터베이스를 오픈하세요" );
        }
    }
    public void executeQuery(String tableName){
        println("executeQuery 호출 됨");

        String sql = "select _id, name, age from " + tableName;
        Cursor cursor = database.rawQuery(sql, 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);
            String age = cursor.getString(2);
            println("레코드#" + i + "id : "+ id +" : " + name + " , " + age);
        }
        cursor.close();
    }

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

}

7) 코드 example 

https://github.com/rain2002kr/SampleDataBase.git

반응형