UserOpenHelperでSQLiteOpenHelperを継承します。
package self.mydbapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by narishige on 2016/11/21.
*/
public class UserOpenHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String CREATE_TABLE =
"create table " + UserContract.Users.TABLE_NAME + " (" +
UserContract.Users._ID + " integer primary key autoincrement," +
UserContract.Users.COL_NAME + "name text," +
UserContract.Users.COL_SCORE + "score integer)";
public static final String INIT_TABLE =
"insert into users (name, score) values " +
"('yoshimoto', 55), " +
"('kimura', 45), " +
"('igarashi', 82)";
public static final String DROP_TABLE =
"drop table if exists users";
public UserOpenHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// create table
sqLiteDatabase.execSQL(CREATE_TABLE);
// init table
sqLiteDatabase.execSQL(INIT_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// drop table
sqLiteDatabase.execSQL(DROP_TABLE);
// onCreate
onCreate(sqLiteDatabase);
}
}
insert, delete, update
UserOpenHelper userOpenHelper = new UserOpenHelper(this);
SQLiteDatabase db = userOpenHelper.getWritableDatabase();
// open db
ContentValues newUser = new ContentValues();
newUser.put(UserContract.Users.COL_NAME, "tanaka");
newUser.put(UserContract.Users.COL_SCORE, "42");
long newID = db.insert(
UserContract.Users.TABLE_NAME,
null,
newUser
);
ContentValues newScore = new ContentValues();
newScore.put(UserContract.Users.COL_SCORE, 100);
int updatedCount = db.update(
UserContract.Users.TABLE_NAME,
newScore,
UserContract.Users.COL_NAME + " = ?",
new String[] {"sakai"}
);
int deletedCount = db.delete(
UserContract.Users.TABLE_NAME,
UserContract.Users.COL_NAME + " = ?",
new String[] {"sakai"}
);
Cursor c = null;
c = db.query(
UserContract.Users.TABLE_NAME,
null, // fields
null, // where
null, // where arg
null, // groupby
null,
null
);
トランザクション
try {
db.beginTransaction();
db.execSQL("update users " +
"set score = score + 10 " +
"where name = 'kaneko'");
db.execSQL("update users " +
"set score = score + 10 " +
"where name = 'muraoka'");
} catch(SQLException e){
e.printStackTrace();
} finally {
db.endTransaction();
}