次のコードでデータベースを作成しました:
public class DataEncryptHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database
// version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "DBSample.db";
Context mContext;
public DataEncryptHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(Model.SQL_CREATE_STORY);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy
// is
// to simply to discard the data and start over
db.execSQL(Model.SQL_DELETE_STORY);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void insertStory(String title, String content) {
DataEncryptHelper mDbHelper = new DataEncryptHelper(mContext);
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(Model.COL_TITLE_STORY, title);
values.put(Model.COL_CONTENT_STORY, content);
// Insert the new row, returning the primary key value of the new row
db.insert(Model.TABLE_STORY, null, values);
}
}
そして、これはクラス Model です:
public class Model {
public static final String TEXT_TYPE = "TEXT";
public static final String INTEGER_TYPE = "INTEGER";
public static final String KEY_TYPE = "KEY";
private static final String COMMA_SEP = ",";
// TABLE STORY
public static final String TABLE_STORY = "Story";
public static final String COL_TITLE_STORY = "title_story";
public static final String COL_CONTENT_STORY = "content_story";
public static final String SQL_CREATE_STORY = "CREATE TABLE " + TABLE_STORY
+ " (" + COL_TITLE_STORY + TEXT_TYPE + COMMA_SEP
+ COL_CONTENT_STORY + TEXT_TYPE + " )";
public static final String SQL_DELETE_STORY = "DROP TABLE IF EXISTS "
+ TABLE_STORY;
}
そして MainActivity で:
DataEncryptHelper dbEncrypt = new DataEncryptHelper(this);
dbEncrypt.insertStory("title1", "content1");
しかし、プロジェクトを実行すると、エラーが表示されます:
(1) 表 Story に title_story という名前の列がありません 挿入エラー title_story=title1 content_story=content1 android.database.sqlite.SQLiteException: 表 Story に title_story という名前の列がありません (コード 1): 、コンパイル中: INSERT INTO Story(title_story,content_story)値 (?,?)