我已经在我的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>
其他回答
Sqlite数据库覆盖两种方法
1) onCreate (): 该方法仅在应用程序第一次启动时调用一次。所以它只调用一次
2) onUpgrade () 当我们改变数据库版本时,这个方法被调用,然后这个方法被调用。它用于改变表结构,如在创建DB Schema后添加新列
Sqliteopenhelper的方法有create方法和upgrade方法,create方法在任何表第一次创建时使用,而upgrade方法将在每次表的列数发生变化时调用。
扩展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()不执行时,数据库已经存在)
onCreate ()
When we create DataBase at a first time (i.e Database is not exists) onCreate() create database with version which is passed in SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) onCreate() method is creating the tables you’ve defined and executing any other code you’ve written. However, this method will only be called if the SQLite file is missing in your app’s data directory (/data/data/your.apps.classpath/databases). This method will not be called if you’ve changed your code and relaunched in the emulator. If you want onCreate() to run you need to use adb to delete the SQLite database file.
onUpgrade()
SQLiteOpenHelper应该调用超级构造函数。 onUpgrade()方法只会在版本整数大于应用程序中运行的当前版本时被调用。 如果希望调用onUpgrade()方法,则需要增加代码中的版本号。