我是Android编程新手。关于如何在使用内部联接时检索单个记录,我遇到了一些问题。从研究中我知道如何使用一个表格,例如
public Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_NAME, KEY_SH_ADDR }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop contact = new Shop(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return shop
return contact;
}
但是当我不得不考虑三张不同的桌子时,我感到很茫然。我已经能够检索所有记录,目前我的代码可以在下面查找单个记录。我已经能够用相应的?
替换id
并且它有效,但我显然不希望这种静态。
//Getting Single Team
public List < Team > getTeam() {
List < Team > teamList = new ArrayList < Team > ();
// Select All Query
String selectQuery = "SELECT teams.id, teams.team_name, teams.image, teams_vs_leagues.points, leagues.league_name " +
"FROM teams_vs_leagues " +
"INNER JOIN teams " +
"ON teams_vs_leagues.team_id = teams.id " +
"INNER JOIN leagues " +
"ON teams_vs_leagues.league_id = leagues.id " +
"WHERE teams.id = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Team team = new Team();
team.setId(Integer.parseInt(cursor.getString(0)));
team.setTeamName(cursor.getString(1));
team.setPath(cursor.getString(2));
team.setPoints(Integer.parseInt(cursor.getString(3)));
team.setLeagueName(cursor.getString(4));
// Adding team to list
teamList.add(team);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return team list
return teamList;
}
public class Team {
String team_name, path, league_name;
int id, league_id, points;
public Team(int keyId, String team_name, String path,
int points, String league_name) {
this.id = keyId;
this.team_name = team_name;
this.path = path;
this.points = points;
this.league_name = league_name;
}
public Team() {}
public Team(int keyId) {
this.id = keyId;
}
public int getId() {
return id;
}
public void setId(int keyId) {
this.id = keyId;
}
public int getLeagueId() {
return league_id;
}
public String getTeamName() {
return team_name;
}
public String getLeagueName() {
return league_name;
}
public void setLeagueName(String league_name) {
this.league_name = league_name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void setTeamName(String team_name) {
this.team_name = team_name;
}
public void setLeague_id(int league_id) {
this.league_id = league_id;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
答案 0 :(得分:1)
因为您正在使用占位符
"WHERE teams.id = ?";
在您的查询中,您需要在rawQuery()
中传递选择参数,以便在执行查询期间,占位符将替换为实际值。
Cursor cursor = db.rawQuery(selectQuery, new String[]{id});
//“id”是您想要传递的值,而不是“?”。您可以对其进行硬编码,也可以将其一直传递到getTeam()
检查this。