我正在使用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);
}
由于某种原因,返回的valus为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);
}
答案 0 :(得分:5)
在命令中添加一个参数方向为:
的附加参数System.Data.ParameterDirection.ReturnValue;
并使用
command.ExecuteNonQuery();
然后在调用ExecuteNonQuery之后从返回值参数中检索返回值。