如何使用C#获取SP的输出值

时间:2010-05-07 06:38:00

标签: c#

我使用以下代码执行MySql的SP并获取输出值。我需要在执行SP后将输出值输出到我的c#。怎么样 ?感谢。

代码:

 public static string GetInsertStatement(string DBName, string TblName, string ColName, string ColValue)
    {
        string strData = "";
        MySqlConnection conn = new MySqlConnection(ConfigurationSettings.AppSettings["Con_Admin"]);
        MySqlCommand cmd = conn.CreateCommand();
        try
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "InsGen";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("in_db", MySqlDbType.VarChar, 20);
            cmd.Parameters["in_db"].Value = DBName;
            cmd.Parameters.Add("in_table", MySqlDbType.VarChar, 20);
            cmd.Parameters["in_table"].Value = TblName;
            cmd.Parameters.Add("in_ColumnName", MySqlDbType.VarChar, 20);
            cmd.Parameters["in_ColumnName"].Value = ColName;
            cmd.Parameters.Add("in_ColumnValue", MySqlDbType.VarChar, 20);
            cmd.Parameters["in_ColumnValue"].Value = ColValue; 
            conn.Open(); 
            cmd.ExecuteNonQuery(); 
            conn.Close();
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return strData;
    }

SP:

  DELIMITER $$

DROP PROCEDURE IF EXISTS `InsGen` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`
(
in_db varchar(20),
in_table varchar(20),
in_ColumnName varchar(20),
in_ColumnValue varchar(20)
)
BEGIN

declare Whrs varchar(500);
declare Sels varchar(500);
declare Inserts varchar(2000);
declare tablename varchar(20);
declare ColName varchar(20);

set tablename=in_table;


# Comma separated column names - used for Select
select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')'))
INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename;


# Comma separated column names - used for Group By
select group_concat('`',column_name,'`')
INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename;


#Main Select Statement for fetching comma separated table values
set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');')
from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";");

PREPARE Inserts FROM @Inserts;
select Inserts;
EXECUTE Inserts;

END $$

DELIMITER ;

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

如果我没有弄错,而不是

  

cmd.ExecuteNonQuery();

有一个“ ExecuteScalar ”,它会返回一个标量值。

答案 2 :(得分:0)

问题是你正在打电话

cmd.ExecuteNonQuery(); 

执行而不回读结果。

查看documentation for Command,特别是以Execute开头的方法,并决定哪一个最适合你