无法从c#执行MySql存储过程

时间:2014-08-07 09:10:01

标签: c# mysql asp.net stored-procedures

在MySql中:

DELIMITER //

DROP PROCEDURE IF EXISTS `testdb`.`Check_UserId_Sproc` //
CREATE PROCEDURE `testdb`.`Check_UserId_Sproc` (IN User_Id NVARCHAR(100))
BEGIN
 select count(*) from demo_user where userid = User_Id;
END //

DELIMITER ;

在C#中:

public DataTable ExecuteParameterizedSelectCommand(string CommandName, CommandType cmdType,MySqlParameter[] param)
        {
            DataTable table = new DataTable();
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

            using(MySqlConnection con = new MySqlConnection(CS))
            {
                using (MySqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = CommandName;
                    cmd.Parameters.AddRange(param);

                    try
                    {
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();
                        }

                        using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                        {
                            da.Fill(table);
                        }
                    }
                    catch
                    {
                        throw;
                    }

                    return table;
                }
            }
        }


    public DataTable checkExistingUserId()
            {
                MySqlDBHelper oHelper = new MySqlDBHelper();
                MySqlParameter[] parameters = new MySqlParameter[]
                {
                    new MySqlParameter("User_Id", 'DemoId')
                };
                return oHelper.ExecuteParameterizedSelectCommand("Check_UserId_Sproc", CommandType.StoredProcedure, parameters);
            }

当我尝试执行 checkExistingUserId()时,我遇到以下异常:

Incorrect number of arguments for PROCEDURE testdb.Check_UserId_Sproc; expected 1, got 0

可能是我犯了一个愚蠢的错误,但我无法弄清楚。我是mysql的新手并试图解决它。

当我调试数组包含参数时,如下图所示,但它不是由SP收集的。

enter image description here

提前致谢

1 个答案:

答案 0 :(得分:0)

在您的代码中:

cmd.CommandType = CommandType.Text;

应该是

cmd.CommandType = cmdType;