我使用以下代码创建了一个数据库:
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);
}
}
这是类模型:
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 的列 Error inserting title_story=title1 content_story=content1 android.database.sqlite.SQLiteException: table Story has no column named title_story (code 1): , while compile: INSERT INTO Story(title_story,content_story)价值观(?,?)