我已经搜索了一段时间,但我找到的答案通常涉及存储过程或不同的功能。
我正在尝试执行读取器并在一个查询中返回一个标量。我以为我可以使用输出参数来完成此操作,但在检查 NULL = @rows_found() 附近的语法时出现异常,因此输出参数似乎未初始化。
基本上我需要知道这是否可行,因为我还没有找到这样有效的代码示例。
command.CommandText = @"
SELECT SQL_CALC_FOUND_ROWS
accounting.*
FROM
accounting
WHERE
transaction_type = @transaction_type
LIMIT
@index, @results;
SET @total_rows = FOUND_ROWS();
";
command.Parameters.AddWithValue("transaction_type", transaction_type);
command.Parameters.AddWithValue("index", index);
command.Parameters.AddWithValue("results", results);
MySqlParameter totalRows = new MySqlParameter("total_rows", 0);
totalRows.Direction = System.Data.ParameterDirection.Output;
command.Parameters.Add(totalRows);
using (MySqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
invoices.Add(new AccountingDataModel(dr));
}
invoices.Total = (int)totalRows.Value;
最佳答案
cmd.Parameters["@output"].Value.ToString()
使用命令对象访问您的输出参数.... 您无法直接访问外部参数。
你应该使用像
invoices.Total = Convert.ToInt32(command.Parameters["total_rows"].Value.ToString())
存储过程示例
MySqlCommand cmd = new MySqlCommand(nameOfStoredRoutine, connection);
cmd.CommandType = CommandType.StoredProcedure;
//input parameters
for (int i = 0; i < (parameterValue.Length / 2); i++)
{
cmd.Parameters.AddWithValue(parameterValue[i, 0], parameterValue[i, 1]);
cmd.Parameters[parameterValue[i, 0]].Direction = ParameterDirection.Input;
parameterList = parameterList + parameterValue[i,0] + " " + parameterValue[i,1] + " ";
}
//single output parameter
cmd.Parameters.AddWithValue("@output", MySqlDbType.Int32);
cmd.Parameters["@output"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery(); //Execute command
return Convert.ToInt32(cmd.Parameters["@output"].Value.ToString());
关于c# - .Net MySql 用户定义变量作为输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592488/