如何从函数中获取值

本文关键字:获取 函数 | 更新日期: 2023-09-27 18:21:26

我在BLL内部的一个类中有一个函数,它返回布尔状态,但我也想获得它从Store过程中获得的输出参数的值,但如何获得?

public Boolean InsertPersonalInfo()
{
    SqlCommand SqlCom = new SqlCommand("InsertPersonalInfo", 
                                       DatabaseConnection.OpenConnection());
    SqlCom.CommandType = CommandType.StoredProcedure;

    SqlParameter SqlParameterPersonalInfoID = new SqlParameter("@PersonalInfoID_Returned", 
                                                       SqlDbType.Int);
    SqlCom.Parameters.Add(SqlParameterPersonalInfoID);
    SqlParameterPersonalInfoID.Direction = ParameterDirection.Output;
    SqlCom.ExecuteNonQuery();
    DatabaseConnection.CloseConnection();

    return ReturnStatus;
} 

现在我想从调用它的.cs页面中获取SqlParameterPersonalInfoID的值,但它也应该返回bool值。

如何从函数中获取值

您可以在C#中使用out参数返回它,这与SQL中的用法几乎相似。

类似于:

public Boolean InsertPersonalInfo(your_parameters, out int personalInfoID)
{
     //your code
    personalInfoID = SqlCom.Parameters["@PersonalInfoID_Returned"].Value;
    return ReturnStatus;
}

然后你称之为:

int id;
bool result = InsertPersonalInfo(...., out id);

有关out参数修饰符的参考,请参阅MSDN。

您需要使用SqlDataReader来读取从查询中返回的值,或者只对单个值进行语法处理,如下所示:

public Boolean InsertPersonalInfo(string NIC, string Name, string FatherHusbandName, DateTime DOB, bool Gender, string Religion, string Domicile, string PhoneResidence,
                                          string PhoneOffice, string Mobile, bool MaritalStatus, string Address, string EmailAddress, bool ComputerLiterate, short UserID)
{
   SqlCommand SqlCom = new SqlCommand("InsertPersonalInfo", DatabaseConnection.OpenConnection());
   SqlCom.CommandType = CommandType.StoredProcedure;

  SqlParameter SqlParameterPersonalInfoID = new SqlParameter("@PersonalInfoID_Returned", SqlDbType.Int);
  SqlCom.Parameters.Add(SqlParameterPersonalInfoID);
  SqlParameterPersonalInfoID.Direction = ParameterDirection.Output;
  var yourVar = SqlCom.Parameters["@PersonalInfoID_Returned"].Value; //<---
  SqlCom.ExecuteNonQuery();
  DatabaseConnection.CloseConnection();

  return ReturnStatus;
}