首页 > 编程 > .NET > 正文

.Net中删除数据前进行外键冲突检测

2024-07-10 13:01:38
字体:
来源:转载
供稿:网友
在编写数据库系统中为了保证系统中数据的一致性最简便且安全的方法就是在dbms中建立外键约束,但删除主键数据时如果违反了外键约束,尽管dbms会给出错误提示,如sql server的提示信息“%1! 语句与 %2! %3! 约束 '%4!' 冲突。该冲突发生于数据库 '%6!',表 '%8!'%10!%11!%13!。”,但这些提示信息对最终用户来说,是不友好的,于是就自己写了个类,用来删除记录时的进行外键冲突检测,代码如下:

using system;
using system.data;
using system.data.sqlclient;
using microsoft.applicationblocks.data;

namespace dataaccess.sqlserverdal
{
///
/// check 的摘要说明。
///
public class check
{
///
/// dbms中保存系统表的
///
const string default_systables = "systables";

#region ckeckfkbegindelete

///
/// 在删除记录之前先检测有无外键冲突
///
/// 事物对象
/// 要执行删除操作的表名
/// 要删除的记录的主键值
/// 返回错误信息
/// true - 无冲突,false - 有冲突
public bool ckeckfkbegindelete(sqltransaction trans, string tablename, string id, ref string errtext)
{
string selectstring; //sql查询语句
string fktablename; //外键表名称
string fkcolumnname; //外键列名称
object obj; //执行sql查询返回值
string description; //外键表含义

int count; //外键表中引用了主键的记录数

string[] tablenames = {"sysforeignkeys"};

dataset ds = builddatatables();

//检索所有此表的外键表
selectstring = "select fkeyid, fkey from sysforeignkeys a, sysobjects b where a.rkeyid = b.id and b.name = @name";

sqlparameter name = new sqlparameter("@name", sqldbtype.varchar);
name.value = tablename;

sqlhelper.filldataset(trans, commandtype.text, selectstring, ds, tablenames, name);

//外键表id
sqlparameter id = new sqlparameter("@id", sqldbtype.int);
//外键列id
sqlparameter colid = new sqlparameter("@colid", sqldbtype.int);
//主键值
sqlparameter keyid = new sqlparameter("@keyid", sqldbtype.int);

//遍历所有的外键表
foreach (datarow dr in ds.tables["sysforeignkeys"].rows)
{
//查询外键表名称
selectstring = "select name from sysobjects where id = @id";
id.value = dr["fkeyid"];
fktablename = sqlhelper.executescalar(trans, commandtype.text, selectstring, id).tostring();

//查询外键列名称
selectstring = "select name from syscolumns where id = @id and colid = @colid";
id.value = dr["fkeyid"];
colid.value = dr["fkey"];
fkcolumnname = sqlhelper.executescalar(trans, commandtype.text, selectstring, id, colid).tostring();

//查询外键表中有没有引用要删除的主键
selectstring = "select count(*) from " + fktablename + " where " + fkcolumnname + " = @keyid";
keyid.value = id;
count = convert.toint32(sqlhelper.executescalar(trans, commandtype.text, selectstring, keyid));

if (count > 0)
{
//查询发生冲突的表的含义,从而给用户发出友好的提示
selectstring = "select description from callcentertables where tablename = @tablename";
sqlparameter tablename = new sqlparameter("@tablename", sqldbtype.varchar);
tablename.value = fktablename;

obj = sqlhelper.executescalar(trans, commandtype.text, selectstring, tablename);

if (obj != null)
description = obj.tostring();
else
description = fktablename;

errtext = "您要删除的数据已在" + description + "中使用,要删除该条数据,请先删除" +
description + "中的相关数据,否则您将无法删除此条记录!";

return false;
}
}

return true;
}

#endregion

#region builddatatables

///
/// 创建外键datatable
///
/// dataset实例
private dataset builddatatables()
{
dataset ds = new dataset();

datatable table;
datacolumncollection columns;

table = new datatable("sysforeignkeys");
columns = table.columns;

columns.add("fkeyid", typeof(system.int32));
columns.add("fkey", typeof(system.int32));
ds.tables.add(table);

return ds;
}

#endregion
}
}



使用该类时需要在dbms中建一张系统表,并维护表中的数据,该表用来记录系统中各用户表的大概含义,用来告诉用户是什么地方发生了冲突:

create table systables
(
id int not null identity(1,1) primary key clustered, /*id*/
tablename varchar(255), /*用户表名称*/
description varchar(255) /*用户表描述*/
)



调用示例:

public bool test()
{
//数据库连接字符串
string connectionstring = "";

using (sqlconnection conn = new sqlconnection(connectionstring))
{
conn.open();
using (sqltransaction trans = conn.begintransaction())
{
try
{
string execsqlstring = "delete from test where id = 1";
string errtext = "";

if (!new check().ckeckfkbegindelete(trans, "test", 1, ref errtext))
{
trans.rollback();
return false;
}

sqlhelper.executenonquery(trans, commandtype.text, execsqlstring);
trans.commit();
return true;
}
catch
{
trans.rollback();
throw;
}
}
}
}



代码中用到ms的sqlhelper类,可以到http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp下载。目前该类仅适用于sql server数据库


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表