sqliteの簡単な使い方。select、insert、delete、update、createなど

androidで付属のDBであるsqliteの簡単な使い方。select、insert、delete、update、createなどができれば基本的には誰でも使いやすいと思う。

データ型

INTEGER 符号付整数
REAL 浮動小数点
TEXT テキスト
BLOB バイナリデータ
NULL NULL

■DB接続 まずDB用のクラスを作る■

public class MyDB extends SQLiteOpenHelper{
final static private int DB_VERSION = 1;//公開後にDBを変更したらDBのバージョンを変更して、アップデートを要求する
public SQLiteDatabase db;
Context context;

public MyDB(Context context) {
super(context, “test.db”, null, DB_VERSION);//DBバージョンはここで設定する。
this.context = context;
db = getWritableDatabase();
}

@Override //DBが未作成だったら実行される。
public void onCreate(SQLiteDatabase db) {
this.db = db;

//DBにアプリで使うテーブルを作っておく
db.execSQL(
“CREATE TABLE IF NOT EXISTS T_DATA ( ” +
“data_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,” +
“type_id INTEGER, ” +
“value REAL, ” +
“up_date TEXT ” +
“)”
);

public void delete( String tableName, int id ) {
db.delete( tableName, “_id=?”, new String[] { Integer.toString( id ) });
}

@Override //バージョンが新しくなってDBをアップグレードすべき時に実行される。
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < newVersion) {

//とりあえず一回削除してからもう一回作る。データを失いたくなかったら「alter table ~」でやると良い。
db.execSQL(“drop table T_DATA”);
db.execSQL(“drop table T_CATEGORY”);
onCreate(db);
}
}}

■利用する insert update delete■

SQLiteDatabaseを取りだして、それを通してDBを操作できる。

日付はTEXT型に”yyyy-MM-dd HH:mm:ss”形式で入れといて、利用する。datetime型とかはない。

SimpleDateFormat sdf1 = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String up_date = sdf1.format(new Date(System.currentTimeMillis()));

db.compileStatementを使うと連続処理がすごく速くなる。

//DB
MyDB mydb = new MyDB(getApplicationContext());
SQLiteDatabase db = mydb.db;
SQLiteStatement stat = db.compileStatement( “insert into T_DATA (type_id,value,up_date) values (?,?,?)” );
try{
SimpleDateFormat sdf1 = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String up_date = sdf1.format(new Date(System.currentTimeMillis()));
db.beginTransaction();// トランザクション開始
stat.bindDouble( 1, 6);
stat.bindDouble( 2, score);
stat.bindString( 3, up_date);
stat.executeInsert();
db.setTransactionSuccessful();//トランザクション成功
}
finally{db.endTransaction();}

■利用する select selectだけは使い方が別 返り値があるから■

db.rawQueryを使ってカーソルを取って「c.moveToFirst()」で最初にし、「c.moveToNext()」で次の行を読み込む。

「c.getColumnIndex(“data_id”)」でカラムのインデックスを取得して、カラムの型に合わせて「c.getLong()」などで値を取りだす。

String sql = “select data_id,value from T_DATA where type_id = ” + type_id + ” order by up_date desc limit 60″;
Cursor c = db.rawQuery(sql, null);
int i = 1;
if(c.moveToFirst()){
do{
long data_id = c.getLong(c.getColumnIndex(“data_id”));
long value = c.getLong(c.getColumnIndex(“value”));
Log.d(“debug”,type_id + “:” + value);
++i;
}while(c.moveToNext());
}
c.close();

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です