2010-06-20 14 views
3

我正在使用MySQL連接器。MySqlCommand調用函數

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

由於某種原因返回的值是空的。我使用正確的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); 
    } 

回答

4

添加附加參數命令的參數方向:

System.Data.ParameterDirection.ReturnValue; 

並使用

command.ExecuteNonQuery(); 

,然後檢索在調用ExecuteNonQuery之後從返回值參數返回值。