所以我有一个方法,使用传入的变量插入数据库,我使用表适配器。
这就是我所拥有的:
public bool Insert(string fname, string lname)
{
try
{
peopleTableAdapters.PeopleTableAdapter peopleTA= new peopleTableAdapters.PeopleTableAdapter();
peopleTA.insertQuery(fname, lname);
}
catch(Exception ex)
{
}
}
在另一个类中我想检索插件是否成功,我知道我需要在Insert方法的try语句中返回一些内容,但是对于插入查询我会返回什么?
答案 0 :(得分:0)
我建议你不要隐藏异常,并在客户端代码中捕获异常。
public void Insert(string fname, string lname)
{
peopleTableAdapters.PeopleTableAdapter peopleTA= new peopleTableAdapters.PeopleTableAdapter();
peopleTA.insertQuery(fname, lname);
}
在客户端代码中:
/* previous code */
try
{
Insert("a", "b");
}
catch(Exception e)
{
//code when insert fails
}
答案 1 :(得分:0)
您应该从insert方法返回 True 或 False 。简单如下,
public bool Insert(string fname, string lname)
{
try
{
peopleTableAdapters.PeopleTableAdapter peopleTA= new peopleTableAdapters.PeopleTableAdapter();
peopleTA.insertQuery(fname, lname);
// return true since no exception occured
return True;
}
catch(Exception ex)
{
return False;
}
}
也许你需要得到例外,在这种情况下尝试下面,
public bool Insert(string fname, string lname, out string message)
{
string message = string.Empty;
try
{
peopleTableAdapters.PeopleTableAdapter peopleTA= new peopleTableAdapters.PeopleTableAdapter();
peopleTA.insertQuery(fname, lname);
// return true since no exception occurred
message = "Success!";
return True;
}
catch(Exception ex)
{
message = "Error! "+ ex.Message.ToString();
return False;
}
}