如何在C#中调用mysql存储过程

时间:2017-04-15 11:09:55

标签: c# mysql call

我想从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 ;

getting error Image

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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