我在从表中删除行时遇到问题。
我有2个表,其定义如下:
private static final String DATABASE_TABLEELEMENTS = "elements";
public static final String KEY_ROWELEMENTID = "_id";
public static final String KEY_STUDYID = "idstudy";
public static final String KEY_ELEMENTCODE = "code_element";
public static final String KEY_ELEMENTNAME = "description_element";
private static final String DATABASE_TABLETIME = "times";
public static final String KEY_ROWTIME = "_id";
public static final String KEY_ELEMENTID = "idelement";
public static final String KEY_HOURDATE = "hour_date";
public static final String KEY_OBSERVEDYTIME = "observedtime";
public static final String KEY_OBSERVEDACTIVITY = "observedactivity";
这两个表都是相关的:
elements._id = times.idelement
我想删除表“times”中的所有行,这些行具有用户选择的表“elements”中的“idstudy”:
为此我创建了以下功能:
public void ResetDataStudies(String selectedid) {
String querytimes = "DELETE FROM "
+ "times"
+ " WHERE "
+ "times.idelement"
+ " IN "
+ "(SELECT "
+ "elements._id"
+ " FROM "
+ "elements"
+ " WHERE "
+ "elements.idstudy = ?)";
ourDatabase.rawQuery(querytimes, new String[] { selectedid });
}
我没有收到特定错误,但在执行之后数据尚未删除。
见下面的数据类型:
db.execSQL(" CREATE TABLE " + DATABASE_TABLEELEMENTS + " (" +
KEY_ROWELEMENTID + " INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT, " +
KEY_ELEMENTCODE + " INTEGER NOT NULL, " +
KEY_ELEMENTNAME + " TEXT, " +
KEY_STUDYID + " TEXT NOT NULL REFERENCES " + DATABASE_TABLEACOUNT + "("+ KEY_ROWSTUDYID +") ON DELETE CASCADE ");
db.execSQL(" CREATE TABLE " + DATABASE_TABLETIME + " (" +
KEY_ROWTIME + " INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT, " +
KEY_HOURDATE + " INTEGER NOT NULL, " +
KEY_OBSERVEDYTIME + " TEXT NOT NULL, " +
KEY_OBSERVEDACTIVITY + " TEXT NOT NULL, " +
KEY_ELEMENTID + " TEXT NOT NULL REFERENCES " + DATABASE_TABLEELEMENTS + "("+ KEY_ROWELEMENTID +") ON DELETE CASCADE ");
}
我已更新了我的语句,但现在我在创建表时收到错误:
cascade语句附近的错误
答案 0 :(得分:0)
创建表时,外键需要为ON DELETE CASCADE
。例如
FOREIGN KEY ("+KEY_ELEMENTID+") REFERENCES "+DATABASE_TABLEELEMENTS+" ("+KEY_ROWELEMENTID+") ON DELETE CASCADE); "
您还必须告诉SQLite强制执行外键(否则会被忽略)。
PRAGMA foreign_keys = ON;