数据库
首页 > 数据库> > .net-MySqlCommand调用函数

.net-MySqlCommand调用函数

作者:互联网

我正在使用MySQL连接器.

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);
}

由于某些原因,返回的值是null.我使用正确的CommandType吗?

如何从.NET调用MySQL函数?

最终的工作版本是:

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);
    }

解决方法:

向命令添加附加参数,其参数方向为:

System.Data.ParameterDirection.ReturnValue;

并使用

command.ExecuteNonQuery(); 

然后在调用ExecuteNonQuery之后从返回值参数中检索返回值.

标签:return-value,call,net,mysql,function
来源: https://codeday.me/bug/20191024/1917197.html