为什么输出参数在c#级别返回0
本文关键字:返回 输出 参数 为什么 | 更新日期: 2023-09-27 18:16:23
我试图从存储过程中获得输出,但在c#中它给了我0。
public short SelectOccupantTypesByOccupantTypeID(Int64 OccupantID)
{
SqlCommand SqlCom = new SqlCommand("SelectOccupantTypesByOccupantTypeID", DatabaseConnection.OpenConnection());
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.Parameters.AddWithValue("@pk_Occupants_OccupantID", OccupantID);
SqlParameter sqlParamOccupantTypeID = new SqlParameter("@OccupantTypeID", SqlDbType.SmallInt);
sqlParamOccupantTypeID.Direction = ParameterDirection.Output;
SqlCom.Parameters.Add(sqlParamOccupantTypeID);
short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value);
SqlCom.ExecuteNonQuery();
DatabaseConnection.CloseConnection();
return OccupantTypeID;
}
试图得到它
protected void ddlOccupants_SelectedIndexChanged(object sender, EventArgs e)
{
Int64 OccupantID= Convert.ToInt64(ddlOccupants.SelectedValue);
Int16 OccupantTypeID= MngOccupants.SelectOccupantTypesByOccupantTypeID(OccupantID);
txtBoxMonthlyInstallment.Text = OccupantTypeID.ToString();
}
SP:
alter PROCEDURE [dbo].[SelectOccupantTypesByOccupantTypeID]
@pk_Occupants_OccupantID bigint,
@OccupantTypeID smallint output
AS
BEGIN
Set @OccupantTypeID= (Select Occupants.OccupantsOccupantTypeID
From Occupants
Where Occupants.pk_Occupants_OccupantID= @pk_Occupants_OccupantID)
return @OccupantTypeID
END
但是sp在sql级别返回正确的值,但在c#级别返回0。为什么?
在执行查询之前正在读取参数的值,请交换顺序。
SqlCom.ExecuteNonQuery();
short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value);
不管你犯了什么"坏习惯",你的连接真的应该被包装在using
语句中,而不是在你的程序中重用。ADO。. NET已经实现了连接池,您不需要自己做,只需根据需要创建短暂的连接,当您处置它们时,它们将返回到池中。