ここでは、SQLiteOpenHelper を拡張したこの例を使用します
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class YourSQLAdapter {
public static final String DBNAME = "filename.db";
public static final String TABLE = "tablename";
public static final int VERSION = 1;
public static final String KEY_ID = "_id";
// Add other fields here
private SQLiteDatabase sqLiteDatabase;
private SQLiteHelper sqLiteHelper;
private Context mContext;
//this is how I write the create db script, you may do it you own way;)
public static String a = "TEXT";
public static String b = "INTEGER";
public static String c = "PRIMARY KEY";
public static String d = "AUTOINCREMENT";
public static String e = " ";
public static String f = ",";
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE IF NOT EXISTS " + TABLE + e + "(" +
KEY_ID + e + b + e + c + e + d + f + e + ");";
public YourSQLAdapter(Context context){
mContext = context;
}
public void close() {
sqLiteHelper.close();
}
public int deleteAll() {
return sqLiteDatabase.delete(TABLE, null, null);
}
public long insert(String value) {
ContentValues cv = new ContentValues();
rooster.put("fieldname(or use its key value)", value);
return sqLiteDatabase.insert(TABLE, null, cv);
}
public YourSQLAdapter openToRead() throws SQLException {
try {
sqLiteHelper = new SQLiteHelper(mContext, DBNAME, null, 1);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
} catch (Exception e){}
return this;
}
public YourSQLAdapter openToWrite() throws SQLException {
try {
sqLiteHelper = new SQLiteHelper(mContext, DBNAME, null, 1);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
} catch (Exception e){}
return this;
}
public Cursor queueAll() {
String[] KEYS = { KEY_ID /* and all other KEYS*/ };
return sqLiteDatabase.query(TABLE, KEYS, null, null, null, null, null);
}
public Cursor queueDay(String query) {
String[] KEYS = { KEY_ID /* and all other KEYS*/ };
return sqLiteDatabase.query(TABLE, KEYS, query, null, null, null, null);
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SCRIPT_CREATE_DATABASE);
}
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {}
}
}
DBを作成するときに使用します
YourSQLAdapter sql = new YourSQLAdapter(context);
sql.openToWrite();
DBから読み取りたい場合は、
YourSQLAdapter sql = new YourSQLAdapter(context);
sql.openToRead();
警告、DB がまだ作成されていない場合、openToRead() で例外が発生します。これは、SQLiteOpenHelper がまだ存在しないことを認識して作成しようとするためです (書き込みできないため、できません)。
お役に立てれば;)