SQLite使用外键

时间:2016-07-30 09:33:27

标签: android sqlite android-sqlite

    String CREATE_FAVOURITES_TABLE = "CREATE TABLE IF NOT EXISTS " +
            TABLE_FAVOURITES + "("
            + COLUMN_ID2 + " INTEGER PRIMARY KEY,"
            + COLUMN_NAME + " TEXT,"
            + COLUMN_POSTCODE + " INTEGER,"
            + COLUMN_DEELGEMEENTE + " TEXT,"
            + COLUMN_GEMEENTE + " TEXT,"
            + COLUMN_ADRES + " TEXT,"
            + COLUMN_USERNAME + " TEXT, "
            + "FOREIGN KEY(" + COLUMN_USERNAME+ ") REFERENCES "
            + TABLE_USERS + "(username) " + ")";
    db.execSQL(CREATE_FAVOURITES_TABLE);

我试图改变这个,所以我可以通过用户的用户名链接这两个表(否则我每次都要运行一个查询来查找用户的用户名,并且用户名是唯一的,因此它不可能在我的数据库中是两个,这可以通过我的应用程序中的检查来阻止。但1)它不再工作了,我的数据库创建语句的最后三行可能不正确,任何人都可以检查吗?

并且2)我想通过用户名找到单个用户的所有收藏夹,所以我写了这段代码:

public void findFavourites(User user,Winkel winkel){

    String selectQuery = "SELECT" + COLUMN_NAME +"," +  COLUMN_ADRES + "," +  COLUMN_GEMEENTE + "," + COLUMN_DEELGEMEENTE + "," +  COLUMN_POSTCODE;
    selectQuery += "FROM" + TABLE_USERS + "," +TABLE_FAVOURITES;
    selectQuery += "WHERE"+ COLUMN_ID+"=" +COLUMN_ID + "AND";

}

同样,最后一行可能不正确,因为我无法弄清楚如何使外键工作(之前他们工作过,但后来我尝试更改它们,因此用户名将被用作外键,而不是ID)。

错误讯息:

SQLiteException: table favorieten has no column named username (code 1):

1 个答案:

答案 0 :(得分:1)

似乎您在第一次运行后添加了该列 然后卸载并重新安装您的应用,将添加新列。