我已经在我的SQLiteOpenHelper onCreate()中创建了我的表

SQLiteException: no such table

or

SQLiteException: no such column

错误。为什么?

注意: (这是每周数十个类似问题的汇总。试图在这里提供一个“规范的”社区wiki问题/答案,以便所有这些问题都可以指向一个很好的参考。)


当前回答

从模拟器或设备卸载应用程序。再次运行应用程序。(OnCreate()不执行时,数据库已经存在)

其他回答

如果你忘记提供一个“name”字符串作为构造函数的第二个参数,它会创建一个“内存中”数据库,当你关闭应用程序时,这个数据库会被擦除。

数据库名必须以.db结尾,查询字符串必须有结束符(;)

SQLiteOpenHelper onCreate()和onUpgrade()回调在数据库实际打开时被调用,例如通过调用getWritableDatabase()。在创建数据库帮助对象本身时,不会打开数据库。

SQLiteOpenHelper数据库文件的版本。版本号是传递给构造函数的int参数。在数据库文件中,版本号存储在PRAGMA user_version中。

onCreate()仅在数据库文件不存在且刚刚创建时运行。如果onCreate()成功返回(不抛出异常),则假定数据库是使用所请求的版本号创建的。作为暗示,你不应该自己在onCreate()中捕获SQLExceptions。

onUpgrade()仅在数据库文件存在但存储的版本号低于构造函数中请求的版本号时调用。onUpgrade()应该将表模式更新到请求的版本。

当在代码(onCreate())中更改表模式时,应该确保数据库已更新。两种主要方法:

Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to delete the database file: Uninstall the application. Use the application manager or adb uninstall your.package.name from the shell. Clear application data. Use the application manager. Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed. For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database. For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

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.