开发者

How to read the output variable from .net c#?

开发者 https://www.devze.com 2023-04-05 12:31 出处:网络
Does anyone know how can I read the output variable from .net c#? Example: If I have the following stored proc which will return the output variables (@customer_id, @customer_name, @customer_address

Does anyone know how can I read the output variable from .net c#?

Example:

If I have the following stored proc which will return the output variables (@customer_id, @customer_name, @customer_address, @customer_age) instead of the select variable, how can I read the output variable with the following?

mySqlCommand.CommandText = "EXEC app_customers @name=" + sName.T开发者_运维问答ext;
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
}


When the result is a single value (or if you're just interested in the first value in the first column), use the method ExecuteScalar.

It returns an object, simply cast it to the expected type.

int id = (int)mySqlCommand.ExecuteScalar();

Note: the way you're invoking a procedure is not the normal way to do it. Set the command to reference the stored procedure, then add appropriate parameters to the command.Parameters collection. Invoking the procedure using "exec ..." is not a best practice and may even leave you vulnerable. If you need more info on executing such a call, start here.

Edit:

If it is truly an output parameter you need to capture (I believe I misread your question), then the above paragraph is even more applicable. Consider this approach:

mySqlCommand.CommandText = "app_customers";
mySqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
mySqlCommand.Parameters.AddWithValue("@name", theValue);
var customerIdParam = mySqlCommand.Parameters.Add("@customer_id", System.Data.SqlDbType.Int);
customerIdParam.Direction = System.Data.ParameterDirection.Output;
// add more parameters, setting direction as appropriate

mySqlCommand.ExecuteNonQuery();
int customerId = (int)customerIdParam.Value;
// read additional outputs
0

精彩评论

暂无评论...
验证码 换一张
取 消