我試圖創建2表之間的關係,但FK不填充。它保持爲空。以下是我的代碼Android的SQLite外鍵不工作
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "LocalRugbyDB.db";
//table names
public static final String TABLE_PLAYER_INFO = "PLAYER_Local";
public static final String TABLE_TEAM_INFO = "TEAM_local";
//add fields to player table
public static final String KEY_PLAYER_ID = "_id";
public static final String KEY_FNAME = "first_name";
public static final String KEY_LNAME = "last_name";
public static final String KEY_AGE = "age";
public static final String KEY_HEIGHT = "height";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_POSITION = "position";
public static final String KEY_TEAM = "team";
public static final String TEAM_ID = "team_id";
// add field to team table
public static final String KEY_TEAM_ID = "_id";
public static final String KEY_TEAMNAME = "team_name";
public MySQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i("onCreateMaybe", "Created");
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_PLAYER_TABLE = "CREATE TABLE " + TABLE_PLAYER_INFO + "("
+ KEY_PLAYER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_FNAME + " TEXT,"
+ KEY_LNAME + " TEXT,"
+ KEY_POSITION + " TEXT,"
+ KEY_HEIGHT + " TEXT,"
+ KEY_AGE + " TEXT,"
+ KEY_WEIGHT + " TEXT,"
+ KEY_TEAM + " TEXT,"
+ TEAM_ID + " integer,"
+ " FOREIGN KEY ("+TEAM_ID+") REFERENCES "+TABLE_TEAM_INFO+" ("+KEY_TEAM_ID+"));";
String CREATE_TEAM_TABLE = "CREATE TABLE " + TABLE_TEAM_INFO + "("
+ KEY_TEAM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TEAMNAME + " TEXT" + ");";
// create books table
db.execSQL("PRAGMA foreign_keys = ON;");
db.execSQL(CREATE_TEAM_TABLE);
db.execSQL(CREATE_PLAYER_TABLE);
}
這裏您可以看到FK列(team_id)未被填充。我沒有得到任何錯誤,並試圖解決這個問題好幾個小時。
你是如何將這些數據?當我這樣做時,我首先創建「外部」行(團隊),並使用生成的FK,然後將行插入從屬表(播放器)中。有可能有這樣做的狡猾的方式,但這是有效的。另外,您可能會添加一些限定符以防止FK爲空。 –