package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * 데이터베이스를 조회하는 방법을 알 수 있습니다. * Mike * */ public class MainActivity extends Activity { private TextView status; public static final String TAG = "MainActivity"; private static String DATABASE_NAME = null; private static String TABLE_NAME = "employee"; private static int DATABASE_VERSION = 1; private DatabaseHelper dbHelper; private SQLiteDatabase db; package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * 데이터베이스를 조회하는 방법을 알 수 있습니다. * Mike * */ public class MainActivity extends Activity { private TextView status; public static final String TAG = "MainActivity"; private static String DATABASE_NAME = null; private static String TABLE_NAME = "employee"; private static int DATABASE_VERSION = 1; private DatabaseHelper dbHelper; private SQLiteDatabase public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); status = (TextView) findViewById(R.id.status); final EditText input01 = (EditText) findViewById(R.id.input01); Button queryBtn = (Button) findViewById(R.id.queryBtn); queryBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { DATABASE_NAME = input01.getText().toString(); boolean isOpen = openDatabase(); if (isOpen) { executeRawQuery(); executeRawQueryParam(); } } }); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); status = (TextView) findViewById(R.id.status); final EditText input01 = (EditText) findViewById(R.id.input01); Button queryBtn = (Button) findViewById(R.id.queryBtn); queryBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { DATABASE_NAME = input01.getText().toString(); boolean isOpen = openDatabase(); if (isOpen) { executeRawQuery(); executeRawQueryParam(); } } }); } 데이터 조회하기 (MainActivity.java)
private void executeRawQueryParam() { println("\nexecuteRawQueryParam called.\n"); String SQL = "select name, age, phone " + " from " + TABLE_NAME + " where age > ?"; String[] args= {"30"}; Cursor c1 = db.rawQuery(SQL, args); int recordCount = c1.getCount(); println("cursor count : " + recordCount + "\n"); for (int i = 0; i < recordCount; i++) { c1.moveToNext(); String name = c1.getString(0); int age = c1.getInt(1); String phone = c1.getString(2); println("Record #" + i + " : " + name + ", " + age + ", " + phone); } c1.close(); } private void executeRawQueryParam() { println("\nexecuteRawQueryParam called.\n"); String SQL = "select name, age, phone " + " from " + TABLE_NAME + " where age > ?"; String[] args= {"30"}; Cursor c1 = db.rawQuery(SQL, args); int recordCount = c1.getCount(); println("cursor count : " + recordCount + "\n"); for (int i = 0; i < recordCount; i++) { c1.moveToNext(); String name = c1.getString(0); int age = c1.getInt(1); String phone = c1.getString(2); println("Record #" + i + " : " + name + ", " + age + ", " + phone); } c1.close(); } private boolean openDatabase() { println("opening database [" + DATABASE_NAME + "]."); dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); return true; } private void executeRawQuery() { println("\n executeRawQuery called.\n"); Cursor c1 = db.rawQuery("select count(*) as Total from " + TABLE_NAME, null); println("cursor count : " + c1.getCount()); c1.moveToNext(); println("record count : " + c1.getInt(0)); c1.close(); } private boolean openDatabase() { println("opening database [" + DATABASE_NAME + "]."); dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); return true; } private void executeRawQuery() { println("\n executeRawQuery called.\n"); Cursor c1 = db.rawQuery("select count(*) as Total from " + TABLE_NAME, null); println("cursor count : " + c1.getCount()); c1.moveToNext(); println("record count : " + c1.getInt(0)); c1.close(); }
private void executeRawQueryParam2() { println("\n executeRawQueryParam2 called.\n"); String[] columns = {"name", "age", "phone"}; String whereStr = "where age > ?"; String[] whereParams = {"30"}; Cursor c1 = db.query(TABLE_NAME, columns, whereStr, whereParams, null, null, null); int recordCount = c1.getCount(); println("cursor count : " + recordCount + "\n"); for (int i = 0; i < recordCount; i++) { c1.moveToNext(); String name = c1.getString(0); int age = c1.getInt(1); String phone = c1.getString(2); println("Record #" + i + " : " + name + ", " + age + ", " + phone); } c1.close(); } private void println(String msg) { Log.d(TAG, msg); status.append("\n" + msg); } groupby 절 having 절 orderby 절
<LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint=“ 데이터베이스명 " android:text="customer.db" android:textSize="16dp" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=“ 질의수행 " android:textStyle="bold" > <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint=“ 데이터베이스명 " android:text="customer.db" android:textSize="16dp" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=“ 질의수행 " android:textStyle="bold" > <ScrollView android:layout_width="match_parent" android:layout_height="match_parent” > <TextView android:layout_width="match_parent“ android:layout_height="match_parent“ android:background="#ff99ccee" android:textColor="#ff0000ff" android:textSize="14dp" > </LinearLayout <ScrollView android:layout_width="match_parent" android:layout_height="match_parent” > <TextView android:layout_width="match_parent“ android:layout_height="match_parent“ android:background="#ff99ccee" android:textColor="#ff0000ff" android:textSize="14dp" > </LinearLayout 데이터 조회하기 (activity_main.xml)
package org.androidtown.database.cursor; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class MainActivity extends Activity { public static final String TAG = "SampleCursorAdapter"; private static String DATABASE_NAME = "employeeDB"; private static String TABLE_NAME = "employee"; private static int DATABASE_VERSION = 1; private DatabaseHelper dbHelper; private SQLiteDatabase db; private TextView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); status = (TextView) findViewById(R.id.status); ListView list = (ListView) findViewById(R.id.list); package org.androidtown.database.cursor; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class MainActivity extends Activity { public static final String TAG = "SampleCursorAdapter"; private static String DATABASE_NAME = "employeeDB"; private static String TABLE_NAME = "employee"; private static int DATABASE_VERSION = 1; private DatabaseHelper dbHelper; private SQLiteDatabase db; private TextView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); status = (TextView) findViewById(R.id.status); ListView list = (ListView) findViewById(R.id.list); boolean isOpen = openDatabase(); if (isOpen) { Cursor cursor = executeRawQueryParam(); startManagingCursor(cursor); String[] columns = new String[] {"name", "age", "phone"}; int[] to = new int[] { R.id.name_entry, R.id.age_entry, R.id.phone_entry }; SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listitem, cursor, columns, to); list.setAdapter(mAdapter); } private boolean openDatabase() { println("opening database [" + DATABASE_NAME + "]."); dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); return true; } boolean isOpen = openDatabase(); if (isOpen) { Cursor cursor = executeRawQueryParam(); startManagingCursor(cursor); String[] columns = new String[] {"name", "age", "phone"}; int[] to = new int[] { R.id.name_entry, R.id.age_entry, R.id.phone_entry }; SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listitem, cursor, columns, to); list.setAdapter(mAdapter); } private boolean openDatabase() { println("opening database [" + DATABASE_NAME + "]."); dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); return true; } 커서어댑터로 뷰에 보여주기 (MainActivity.java) 액티비티 수명주기에 따라 cursor 를 자동 반응하게 함 액티비티가 onPause() 상태 : 커서 비활성화 onResume() 상태 : 커서 활성화
private Cursor executeRawQueryParam() { println("\nexecuteRawQueryParam called.\n"); String SQL = "select _id, name, age, phone " + " from " + TABLE_NAME + " where age > ?"; String[] args= {"10"}; Cursor c1 = db.rawQuery(SQL, args); return c1; } private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } private Cursor executeRawQueryParam() { println("\nexecuteRawQueryParam called.\n"); String SQL = "select _id, name, age, phone " + " from " + TABLE_NAME + " where age > ?"; String[] args= {"10"}; Cursor c1 = db.rawQuery(SQL, args); return c1; } private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { println("creating table [" + TABLE_NAME + "]."); try { String DROP_SQL = "drop table if exists " + TABLE_NAME; db.execSQL(DROP_SQL); } catch(Exception ex) { Log.e(TAG, "Exception in DROP_SQL", ex); } String CREATE_SQL = "create table " + TABLE_NAME + "(" + " _id integer PRIMARY KEY autoincrement, " + " name text, " + " age integer, " + " phone text)"; try { db.execSQL(CREATE_SQL); } catch(Exception ex) { Log.e(TAG, "Exception in CREATE_SQL", ex); } println("inserting records."); try { db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('John', 20, ' ');" ); db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('Mike', 35, ' ');" ); db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('Sean', 26, ' ');" ); } catch(Exception ex) { Log.e(TAG, "Exception in insert SQL", ex); } public void onCreate(SQLiteDatabase db) { println("creating table [" + TABLE_NAME + "]."); try { String DROP_SQL = "drop table if exists " + TABLE_NAME; db.execSQL(DROP_SQL); } catch(Exception ex) { Log.e(TAG, "Exception in DROP_SQL", ex); } String CREATE_SQL = "create table " + TABLE_NAME + "(" + " _id integer PRIMARY KEY autoincrement, " + " name text, " + " age integer, " + " phone text)"; try { db.execSQL(CREATE_SQL); } catch(Exception ex) { Log.e(TAG, "Exception in CREATE_SQL", ex); } println("inserting records."); try { db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('John', 20, ' ');" ); db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('Mike', 35, ' ');" ); db.execSQL( "insert into " + TABLE_NAME + "(name, age, phone) values ('Sean', 26, ' ');" ); } catch(Exception ex) { Log.e(TAG, "Exception in insert SQL", ex); }
public void onOpen(SQLiteDatabase db) { println("opened database [" + DATABASE_NAME + "]."); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + "."); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } private void println(String msg) { Log.d(TAG, msg); status.append("\n" + msg); public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
<LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:layout_width="match_parent" android:layout_height="wrap_content" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff99ccee" android:textColor="#ff0000ff" android:textSize="18dp" > 커서어댑터로 뷰에 보여주기 (activity_main.xml)
<LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" /> 커서어댑터로 뷰에 보여주기 (listitem.xml)