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

SQLiteException: no such table

or

SQLiteException: no such column

错误。为什么?

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


当前回答

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

其他回答

从模拟器或设备卸载应用程序。再次运行应用程序。(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

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