SQLite 从之前的插入中插入 id 以填充另一个 table 中的列值

SQLite insert id from previous insert to populate value of column in another table

我是 android 编程和 SQLite 的新手,遇到了障碍。我有 3 table 个问题; teamsleagues 和一个名为 teams_vs_leagues 的查找 table,它包含球队的 ID 和联赛的 ID,因此它们是相关联的。以下是 table 的设计:

//Create teams Table
private static final String CREATE_TEAMS_TABLE = "CREATE TABLE "
        + TEAMS_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + TEAM_NAME + " TEXT,"
        + IMAGE + " TEXT" + ")";

//Create leagues Table
private static final String CREATE_LEAGUES_TABLE = "CREATE TABLE "
        + LEAGUES_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + LEAGUE_NAME + " TEXT" + ")";

//Create teams_vs_leagues Table
private static final String CREATE_TEAMS_VS_LEAGUES_TABLE = "CREATE TABLE "
        + TEAMS_VS_LEAGUES_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + TEAM_ID + " INTEGER,"
        + LEAGUE_ID + " INTEGER,"
        + POINTS + " INTEGER"+ ")";

目前我的新增队伍方法如下:

public boolean createTeam(String team_name, String image, String team_id, String league_id, String points) {
 SQLiteDatabase db = this.getWritableDatabase();

 ContentValues values = new ContentValues();

 values.put(TEAM_NAME, team_name);
 values.put(IMAGE, image);

 long result = db.insert(TEAMS_TABLE, null, values);

 if (result == -1)
  return false;
 else
  return true;
}

如何将 TEAM_ID 添加到 teams_vs_league table 作为上面插入的 ID?任何帮助将不胜感激。

insert() 方法 returns 新插入行的行 ID,如果发生错误则为 -1。

所以你可以修改你的代码:

if (result == -1)
    return false;
else
    //create the record in the teams_vs_leagues here
    //using result as TEAM_ID and league_id as LEAGUE_ID 

    return true;
}

根据 SQLite API Android SQLite API,插入方法 returns 新插入行的行 ID,如果发生错误则为 -1。

因此,您可以对代码进行如下更改:

  long result = db.insert(TEAMS_TABLE, null, values);

  if (result == -1) { 
      //throw error here
      return false;
   } else { 
     //result contains the id needed
     //do something
     return true;
  }

干杯!编程愉快!