在c#中调用mysql存储过程

时间:2014-05-07 02:37:55

标签: c# mysql sql

这是我的存储过程:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(goals = ''',
      goals,
      ''', round(value, 2), NULL)) AS ',
      goals
    )
  ) INTO @sql
FROM sgwebdb.dim_module;
SET @sql = CONCAT('SELECT alternative, ', @sql, ' FROM sgwebdb.dim_module GROUP BY 
alternative');

prepare stmt from @sql;
execute stmt;

我需要在下面的代码中调用此过程,而不是在MySQL查询(query1)下面调用

C#代码 - >

protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid(); 
    }

    private void BindGrid()
    {
        string query1 = "SELECT alternative as 'Alternative',max( case when goals='G1' then round( value, 2 ) end ) as 'Goal 1',max( case when goals='G2' then round( value, 2 ) end ) as 'Goal 2',max( case when goals='G3' then round( value, 2 ) end ) as 'Goal 3',max( case when goals='G4' then round( value, 2 ) end ) as 'Goal 4' from sgwebdb.dim_module group by alternative";

        this.GridView1.DataSource = DataManager.DatabaseManager.GetOrCreateConnection(DataManager.DatabaseManager.ConnectionType.MySQL).GetData(query1);
        GridView1.DataBind();
        for (int n = 0; n < (GridView1.Rows.Count - 1); n++)
        {
                            Textval.Text = GridView1.Rows[n].Cells[1].Text;
                            double gdval = Convert.ToDouble(Textval.Text);
         }


        }

在c#代码中取代Query1如何在MySQL程序之上调用?

1 个答案:

答案 0 :(得分:2)

创建MySqlCommand对象时,需要在CommandText属性中设置存储过程的名称,并将CommandType属性设置为CommandType.StoredProcedure

以下是设置MySqlCommand对象的代码示例:

MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandText = "NameOfYourStoredProcedure";
command.CommandType = CommandType.StoredProcedure;

添加参数时需要注意的一点是,存储过程中参数的名称必须与添加到Parameters对象的MySqlCommand集合中的参数名称相匹配。