首页 > 代码库 > Android sqlite 级联删除更新
Android sqlite 级联删除更新
============问题描述============
大概是一个租房管理系统,我要求的是
delete from house where houseName = ? 之后,可以级联删除与该houseName有关的内容
This is my tables building in java:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sqlhouse = "create table house (houseName char(20) primary key, number int not null);";
db.execSQL(sqlhouse);
String sqlroom = "create table room(houseName char(20),roomNumber integer ,waterConsumption int not null"
+ ",electricityConsumption int not null,primary key(houseName,roomNumber),"
+ "foreign key (houseName) references house (houseName) on delete cascade on update cascade);";
db.execSQL(sqlroom);
String sqlrenter = "create table renter(Id char(18) primary key,name char(20) not null,phoneNumber char(11) not null)";
db.execSQL(sqlrenter);
String sqlcheckindocument = "create table CheckInDocument(Id char(18),houseName char(20),roomNumber int,deposit int not null,rental int not null,startingDate Date not null,surfing int not null,waterFare float not null,electricityFare float not null,totalAmount float,primary key (houseName,roomNumber),foreign key (Id) references renter(Id) on delete cascade on update cascade,foreign key(houseName,roomNumber) references room(houseName,roomNumber) on delete cascade on update cascade)";
db.execSQL(sqlcheckindocument);
String sqlcheckoutdocument = "create table checkOutDocument(houseName char(20),roomNumber char(10),checkOutDate Date not null,amount int,waterConsumption int not null,electricityConsumption int not null,"
+ "primary key (houseName,roomNumber),foreign key(houseName,roomNumber) references room(houseName,roomNumber) on delete cascade on update cascade)";
db.execSQL(sqlcheckoutdocument);
String sqlrentingdocument = "create table rentingDocument(houseName char(20),roomNumber char(10),waterConsumption int not null,electricityConsumption int not null,rentingDate Date not null,amount int not null,"
+ "primary key (houseName,roomNumber),foreign key(houseName,roomNumber) references room(houseName,roomNumber) on delete cascade on update cascade)";
db.execSQL(sqlrentingdocument);
}
在手机上运行后,我把数据库导入电脑的sqlite3,y然后执行删除语句,完全没问题。
但是在手机上,我执行删除houseName之后,发现不能实现级联删除,请大神指点!!!!!
============解决方案1============
1.
试一下在打开数据库以后执行db.execSQL("PRAGMA foreign_keys=ON");这个语句的作用是打开外键支持。
2.
或者在一个事务里从各个表删除记录。
============解决方案2============
sqlite自从3.6.19之后才支持外键,但是android在2.1之前都是用的sqlite3.5,为了兼容老版本的,在android里的sqlite外键默认关闭
如果你确定你支持支android2.2以上的应用,那么你就可以在执行以下db.execSQL("PRAGMA foreign_keys=ON");手动打开支持
Android sqlite 级联删除更新
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。