我已经在我的SQLiteOpenHelper onCreate()中创建了我的表
SQLiteException: no such table
or
SQLiteException: no such column
错误。为什么?
注意: (这是每周数十个类似问题的汇总。试图在这里提供一个“规范的”社区wiki问题/答案,以便所有这些问题都可以指向一个很好的参考。)
我已经在我的SQLiteOpenHelper onCreate()中创建了我的表
SQLiteException: no such table
or
SQLiteException: no such column
错误。为什么?
注意: (这是每周数十个类似问题的汇总。试图在这里提供一个“规范的”社区wiki问题/答案,以便所有这些问题都可以指向一个很好的参考。)
当前回答
在我的例子中,我从XML-file中获取带有<string-array>的项,其中存储<item>s。在这些<item>s我持有SQL字符串和应用databaseBuilder.addMigrations(迁移)一个接一个。我犯了一个错误,忘记在引用前添加\,得到了异常:
android.database.sqlite.SQLiteException:没有这样的列:some_value(代码1 SQLITE_ERROR):,而编译:INSERT INTO table_name(id, name) VALUES(1, some_value)
所以,这是一个正确的变体:
<item>
INSERT INTO table_name(id, name) VALUES(1, \"some_value\")
</item>
其他回答
从模拟器或设备卸载应用程序。再次运行应用程序。(OnCreate()不执行时,数据库已经存在)
扩展SQLiteOpenHelper时要记住的要点
super(context, DBName, null, DBversion); - This should be invoked first line of constructor override onCreate and onUpgrade (if needed) onCreate will be invoked only when getWritableDatabase() or getReadableDatabase() is executed. And this will only invoked once when a DBName specified in the first step is not available. You can add create table query on onCreate method Whenever you want to add new table just change DBversion and do the queries in onUpgrade table or simply uninstall then install the app.
当需要创建表时,第一次调用onCreate。我们需要重写这个方法,在这里我们编写了由SQLiteDatabase执行的表创建脚本。execSQL方法。在第一次部署中执行后,此方法将不再被调用。
onUpgrade 当数据库版本升级时调用此方法。假设第一次部署时,数据库版本为1,在第二次部署时,数据库结构发生了变化,例如在表中增加了额外的列。假设数据库版本现在是2。
您可以创建数据库和表
public class DbHelper extends SQLiteOpenHelper {
private static final String DBNAME = "testdatbase.db";
private static final int VERSION = 1;
public DbHelper(Context context) {
super(context, DBNAME, null, VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table BookDb(id integer primary key autoincrement,BookName text,Author text,IssuedOn text,DueDate text,Fine text,Totalfine text");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS BookDb");
onCreate(db);
}
}
注意:如果您想创建另一个表或添加列或没有这样的表,只需增加VERSION
数据库名必须以.db结尾,查询字符串必须有结束符(;)