Android Debug Bridge (adb)を使って、SQLiteを操作する。
2012年2月3日(金) 2:32 PM
Android Debug Bridge (adb)は、デバッグの際に使用するエミュレーターやアンドロイド端末を操作することができるコマンドラインツールです。
adbを使うことで、SQLiteをコマンドライン上で操作することができます。

①まず、操作したデータベースがあるアプリをデバッグし、エミュレータを立ち上げておきます。
②次に、「コマンドプロンプト」から、カレントディレクトリーを、Android SDK内の「platform-tools」に変更します。
(例:「cd C:\Android\android-sdk-windows\platform-tools」)
③「adb shell」と入力して、adb shellを起動します。
(*うまくできない場合は、「プログラムとファイルの検索」(Windows 7)から「adb shell」と入力しても実行可能です。)
④すると、「#」の文字が出てくるので、「# cd /data/data/(パッケージ名)/databases」と入力して、カレントディレクトリーを変更します。
(例:「cd /data/data/com.sample.android.dbsamplea/databases」)
④「# sqlite3 (データベース名)」と入力します。
(例: 「# sqlite3 testdb」)
⑤「sqlite>」の文字が出てくるので、SQL文を書くと、SQLiteを操作することができます。
(例:「sqlite> SELECT * from testtb;」と書くと、testtbテーブルにあるデータが列挙されます。 )
⑥終了するときは、「sqlite> .exit」、「# exit」で終了します。
SQLiteの使い方(SQLiteOpenHelperクラス)~その2~
2012年2月2日(木) 11:06 AM
SQLiteの使い方(SQLiteOpenHelperクラス)~その1~で作ったサンプルに、SQLiteのレコードの更新機能と削除機能を追加してみました。
前回のサンプルと同じように、エディットテキストに入力して、「追加」ボタンを押すと、データがデータベースに追加されていきます。

「削除」ボタンを押すと、ID番号が一番大きいIDのデータが削除されます。

「更新」ボタンを押すと、ID番号が一番大きいIDのデータが「更新しました」に変わります。

「削除」ボタンを押すと、ID番号が一番大きいIDのデータが削除されます。
◆◆◆データベース(レコード)の更新◆◆◆
db.update(“testtb”, values, “_id = ?”, new String[] {“1”});
第一引数:テーブル名(String型)
第二引数:カラム値を格納したContentValues型の引数(ContentValues型)
第三引数、第四引数:SQLのWHERE条件文を作成するための引数。(String型、String [] 型)
第三引数、第四引数は、_id=1とかcomment=2などの簡単な条件文じゃないと、デバックが通りませんでした。max関数など複雑な条件文にするときはdb.execSQL(“”);を利用した方がいいかもしれないです。
◆◆◆データベース(レコード、テーブル)の削除◆◆◆
db.delete(“testtb”, “_id = ?”, new String[] {“1”});
第一引数:テーブル名(String型)
第二引数、第三引数:SQLのWHERE条件文を作成するための引数。(String型、String [] 型)
第二引数、第三引数を両方とも「null」にすると、すべてのレコードが削除されます。
◆◆◆データベースの削除◆◆◆
File file = new File(“/data/data/com.sample.android.dbsamplea/databases/testdb”);
file.delete();
データベースそのものを削除するときは、file.delete();を使います。最初に、new File(“/data/data/(パッケージ名)/databases/(データベース名)“)でFileオブジェクトを生成し、その後delete();を使って削除します。
(File(“”)の引数は、データベースがあるパスです。Eclipseで、デバッグする場合は、DDMS画面で確認できます。)
↓↓↓修正または追加したファイルのコードは以下の通りです。↓↓↓
(それ以外は、SQLiteの使い方(SQLiteOpenHelperクラス)~その1~で作ったものと同じです。)
「DBSampleA.java」のサンプルコード
package com.sample.android.dbsamplea; import java.io.File; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class DBSampleA extends Activity implements View.OnClickListener{ private Button btn[] = new Button[3]; private EditText edittext; private TextView textview; private MyDBHelper myhelper; private String str; private int num = 0; private static SQLiteDatabase db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //ボタンの生成 btn[0] = (Button)findViewById(R.id.AddButton); btn[0].setOnClickListener(this); btn[1] = (Button)findViewById(R.id.UpdateButton); btn[1].setOnClickListener(this); btn[2] = (Button)findViewById(R.id.RemoveButton); btn[2].setOnClickListener(this); //エディットテキストの生成 edittext = (EditText)findViewById(R.id.AddEditText); //テキストビューの生成 textview = (TextView)findViewById(R.id.MyTextView); //データベースヘルパーの生成 myhelper = new MyDBHelper(this); db = myhelper.getWritableDatabase(); //db.delete("testtb", null, null); Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null); startManagingCursor(c); str = "データベース一覧\n"; while(c.moveToNext()) { str += c.getString(c.getColumnIndex("_id")) + ":" + c.getString(c.getColumnIndex("comment")) + "\n"; num++; } textview.setText(str); } //ボタンクリックイベントの処理 public void onClick(View v) { ContentValues values = new ContentValues(); if(v == btn[0]) { values.put("comment", edittext.getText().toString()); db.insert("testtb", null, values); num++; } else if(v == btn[1]) { String[] args = {String.valueOf(num)}; values.put("comment", "更新しました"); db.update("testtb", values, "_id = ?", args); } else if(v == btn[2]) { String[] args = {String.valueOf(num)}; db.delete("testtb", "_id = ?", args); num--; } Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null); startManagingCursor(c); str = "データベース一覧\n"; while(c.moveToNext()) { str += c.getString(c.getColumnIndex("_id")) + ":" + c.getString(c.getColumnIndex("comment")) + "\n"; } textview.setText(str); } @Override public void onDestroy() { super.onDestroy(); myhelper.close(); //データベース削除 File file = new File("/data/data/com.sample.android.dbsamplea/databases/testdb"); file.delete(); } }
「main.xml」のサンプルコード
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/AddEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/AddButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="追加" /> <Button android:id="@+id/UpdateButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="更新" /> <Button android:id="@+id/RemoveButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="削除" /> </LinearLayout> <TextView android:id="@+id/MyTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
SQLiteの使い方(SQLiteOpenHelperクラス)~その1~
2012年2月1日(水) 2:45 PM
SQLiteのデータベースを作成し、エディットテキストから入力したデータを登録し、画面に表示するサンプルを作ってみました。
「データベース一覧」に、データベースに登録されているデータが表示されます。

「five」と入力して、追加ボタンを押すと、一覧に「5:five」と表示され、データベースにデータが追加されていきます。

◆◆◆SQLiteOpenHelperクラスを継承したクラスの実装◆◆◆
public class MyDBHelper extends SQLiteOpenHelper {
public MyDBHelper(Context context) {
//DBを作成
super(context, “testdb”, null , 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(“CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)”);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
「onCreate」は、データベースを作成した時に呼び出されるメソッドで、「onUpgrade」は、データベースをバージョンアップした時に呼び出されるメソッド。「onCreate」に、データベースのテーブルを作成するコードを書くことが多い。
◆◆◆データベースの生成◆◆◆
public MyDBHelper(Context context) {
//ストレージ(ローカルファイル)にDBを作成
super(context, “testdb”, null , 1);
}
第一引数:コンテキスト
第二引数:データベースの名前(String型)
第三引数:とりあえず null にしておけば大丈夫だと思います。(CursorFactory型)
第四引数:データベースのバージョン番号(int型)
◆◆◆SQLの実行◆◆◆
db.execSQL(“CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)”);
” “の中にSQL文を書いて実行することができる。テーブルを作成するだけでなく、レコードの追加(INSERT)、更新(UPDATE)、削除(DELETE)なども実行できる。ただし、検索(SELECT)は発行されないらしいので、db.queryを使う。
◆◆◆データベース(レコード)の削除◆◆◆
db.delete(“testtb”, null, null);
第一引数:テーブル名
第二引数、第三引数:SQLのWHERE条件文を作成するための引数。
例えば
db.delete(“testtb”, “_id = ?”, new String[]{“1”});
を実行すると、_id=1のレコードが削除される。
(引数を二つに分けているのは、SQLインジェクション対策だと思われます。)
◆◆◆データベース(レコード)の検索◆◆◆
Cursor c = db.query(“testtb”, new String[] {“_id”, “comment”}, null, null, null, null, null);
第一引数:テーブル名
第二引数:取得するカラム名
第三引数、第四引数:条件文作成のための引数
第五引数:groupBy句の引数
第六引数:having句の引数
第七引数:orderBy句の引数
戻り値はCusor型のオブジェクト
◆◆◆カーソルの使い方◆◆◆
startManagingCursor(c);
while(c.moveToNext()) {
/*データがなくなるまで、ループ処理が繰り返される。
str += c.getString(c.getColumnIndex(“_id”)) + “:” +
c.getString(c.getColumnIndex(“comment”)) + “\n”;
}
startManagingCursor(Cursor c)は、カーソルを自動で管理してくれるメソッドで、このメソッドを呼び出した後、c.moveToNextを呼び出すと、カーソルが最初のデータに移動します。そのあとに、c.moveToNextを呼び出すとデータがなくなるまで、次のデータにカーソルが移動します。
(c.moveToFirstでも、最初のデータに移動することができますが、カーソルを使い終わった後に、c.closeをする必要があります。これをしないと、デバッグの際にSQLiteCursor.finalize()で強制終了してしまいます。startManagingCursor(Cursor c)は、カーソルのcloseを自動でしてくれるみたいなので、必要ありません。)
◆◆◆データベース(レコード)の追加◆◆◆
db.insert(“testtb”, null, values);
第一引数:テーブル名(String型)
第二引数:nullColumnHack。とりあえずnullで大丈夫だと思います。(String型)
第三引数:カラム値を格納したContentValues型の引数(ContentValues型)
◆◆◆ContentValuesに値を追加する。◆◆◆
ContentValues values = new ContentValues();
values.put(“comment”, edittext.getText().toString());
第一引数:キー値(カラム値)(String型)
第二引数:値(String型、integer型、Long型など)
↓↓↓修正または追加したファイルのコードは以下の通りです。↓↓↓
(それ以外は、新規プロジェクトを生成した時のものと同じです。)
「DBSampleA.java」のサンプルコード
package com.sample.android.dbsamplea; import java.io.File; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class DBSampleA extends Activity implements View.OnClickListener{ private Button btn; private EditText edittext; private TextView textview; private MyDBHelper myhelper; private String str; private static SQLiteDatabase db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //ボタンの生成 btn = (Button)findViewById(R.id.AddButton); btn.setOnClickListener(this); //エディットテキストの生成 edittext = (EditText)findViewById(R.id.AddEditText); //テキストビューの生成 textview = (TextView)findViewById(R.id.MyTextView); //データベースヘルパーの生成 myhelper = new MyDBHelper(this); db = myhelper.getWritableDatabase(); //データベーステーブルクリア db.delete("testtb", null, null); //データベースのデータを読み取って表示する。 Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null); startManagingCursor(c); str = "データベース一覧\n"; while(c.moveToNext()) { str += c.getString(c.getColumnIndex("_id")) + ":" + c.getString(c.getColumnIndex("comment")) + "\n"; } textview.setText(str); } //ボタンクリックイベントの処理 public void onClick(View v) { //データベースに、データを登録。 ContentValues values = new ContentValues(); values.put("comment", edittext.getText().toString()); db.insert("testtb", null, values); //データベースのデータを読み取って表示する。 Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null); startManagingCursor(c); str = "データベース一覧\n"; while(c.moveToNext()) { str += c.getString(c.getColumnIndex("_id")) + ":" + c.getString(c.getColumnIndex("comment")) + "\n"; } textview.setText(str); } @Override public void onDestroy() { super.onDestroy(); myhelper.close(); //データベース削除 File file = new File("/data/data/com.sample.android.dbsamplea/databases/testdb"); file.delete(); } }
「MyDBHelper.java」のサンプルコード(追加ファイル)
package com.sample.android.dbsamplea; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MyDBHelper extends SQLiteOpenHelper { public MyDBHelper(Context context) { //DBを作成 super(context, "testdb", null , 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
「main.xml」のサンプルコード
< ?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <edittext android:id="@+id/AddEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <button android:id="@+id/AddButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="追加" /> <textview android:id="@+id/MyTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </linearlayout>