我使用以下代码创建了一个数据库:
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的列 插入title_story = title1 content_story = content1时出错 android.database.sqlite.SQLiteException:table Story没有列 命名为title_story(代码1):,同时编译:INSERT INTO Story(title_story,content_story)VALUES(?,?)
答案 0 :(得分:1)
在字段名称后添加空格
// 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;