【问题标题】:How to call mysql stored procedure in C#如何在C#中调用mysql存储过程
【发布时间】:2017-04-15 11:09:55
【问题描述】:

我想从 c# 调用 Mysql 存储过程。我在 mysql 查询浏览器中运行相同的程序。这是关于从给定的输入年、月、日和当前日期获取到期日期。 This is the output

      DELIMITER $$

         DROP PROCEDURE IF EXISTS `passbook`.`maturity_date` $$
         CREATE DEFINER=`root`@`localhost` PROCEDURE `maturity_date`(IN `stdate` 
         DATE, IN `adyear` INT(4), IN `amonth` INT(2), IN `adays` INT(2), INOUT 
         `matdate` DATE)
         NO SQL
         Begin
         declare new_date , pstdate date;

         set new_date = stdate;

          if adyear > 0 then

          SELECT date_add(stdate, INTERVAL adyear year) into pstdate;

          set new_date = pstdate;
          end if;


           if amonth > 0 then

SELECT date_add(new_date, INTERVAL amonth MONTH) into pstdate;
set new_date = pstdate;
end if;

if adays > 0 then

SELECT date_add(new_date, INTERVAL adays DAY) into pstdate;
set new_date = pstdate;
end if;


Set matdate = new_date;
Select matdate;
end $$

DELIMITER ;

【问题讨论】:

  • 很高兴知道您想要的输出、集合、数据表等。您的 C# 是什么样的?

标签: c# mysql call


【解决方案1】:

试试这个:

            var ConnectionString="Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword";            
            var sqlParameters = new List<SqlParameter>();
            var storedProcedureName = "SPName";

    //add parameters with value and type here
            sqlParameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, ParameterName = "@adyear", Value = adyear});
            sqlParameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, ParameterName = "@amonth", Value = amonth});
            sqlParameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, ParameterName = "@adys ", Value = adys });

    //execute store procedure here
            using (var connection = new SqlConnection(ConnectionString))
            using (var command = new SqlCommand(storedProcedureName, connection) { CommandTimeout = 160, CommandType = commandType })
            using (var dataAdaptor = new SqlDataAdapter(command))
            {
                command.Parameters.AddRange(sqlParameters);

                connection.Open();
                dataAdaptor.Fill(dS);
            }

您也可以使用Mysql.Data 我相信这是最简单的方法。您不需要其他任何东西来使用 mysql 数据库。

PM> Install-Package MySql.Data

您可以将连接字符串存储在文件中。只需创建一个文件并将连接字符串放在上面即可。然后在静态类中阅读它。像这样:

CS = File.ReadAllText(YourDataBaseConfigFilePath);

然后将其用作您的连接字符串。

【讨论】:

  • 你好,在哪里添加参数adyear,amonth,adys ??
  • 谢谢@Mohammad,我会去看看
  • 不客气。也请考虑使用 Mysql.Data
  • 我收到错误消息。我无法在此处显示错误图像。所以我在这里发布修改后的代码。也无法在这里发布代码。 :(
  • 嗨@mohammad 在哪里定义连接字符串?它如何知道 mysql 服务器、架构等? .请指导。
猜你喜欢
  • 1970-01-01
  • 2012-06-15
  • 2018-12-07
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多