简体   繁体   中英

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

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.Text;
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM