Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySqlCommand call function

I am using the MySQL Connector.

using (MySqlConnection connection = new MySqlConnection("..."))
{
    connection.Open();
    MySqlCommand command = new MySqlCommand();
    command.Connection = connection;
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "FN_NEW";
    command.Parameters.AddWithValue("P_SESSION_ID", sessionId);
    command.Parameters.AddWithValue("P_NAME", deckName);
    object result = command.ExecuteScalar(); // returns NULL !!!!!!!!!
    return Json(result);
}

For some reason the returned valus is null. Am I using the right CommandType?

How I can call a MySQL function from .NET?

The final working version is:

using (MySqlConnection connection = new    MySqlConnection(GetConnectionString().ConnectionString))
    {
        connection.Open();
        MySqlCommand command = new MySqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "FN_NEW";
        command.Parameters.AddWithValue("P_SESSION_ID", sessionId);
        command.Parameters.AddWithValue("P_NAME", deckName);
        MySqlParameter returnParam = command.Parameters.Add("@RETURN_VALUE", MySqlDbType.Int32);
        returnParam.Direction = System.Data.ParameterDirection.ReturnValue;            
        command.ExecuteNonQuery();
        NewDeckReturnCode result = (NewDeckReturnCode)returnParam.Value;
        return Json(result);
    }
like image 656
Gad D Lord Avatar asked Mar 23 '26 11:03

Gad D Lord


1 Answers

Add an additional parameter to the command with a parameter direction of:

System.Data.ParameterDirection.ReturnValue;

And use

command.ExecuteNonQuery(); 

And then retrieve the return value from the return value parameter after calling ExecuteNonQuery.

like image 54
Chris Baxter Avatar answered Mar 25 '26 01:03

Chris Baxter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!