如何在C#中调用mySQL存储函数?

时间:2010-07-12 12:17:59

标签: c# mysql

我想在C#中调用存储的函数。我需要文章和一些例子。

5 个答案:

答案 0 :(得分:6)

它几乎与您调用SQL Server存储过程的方式相同:

using(MySqlConnection conn = new MySqlConnection(connString))
{
    MySqlCommand command = new MySqlCommand("spSomeProcedure;", conn);
    command.CommandType = System.Data.CommandType.StoredProcedure;

    // Add your parameters here if you need them
    command.Parameters.Add(new MySqlParameter("someParam", someParamValue));

    conn.Open();

    int result = (int)command.ExecuteScalar();
}

答案 1 :(得分:1)

http://forums.asp.net/p/988462/1278686.aspx

    MySqlCommand cmd = new MySqlCommand("DeleteMessage", new MySqlConnection(GetConnectionString()));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new MySqlParameter("param1", MessageItem.Entry_ID));
    cmd.Connection.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();

答案 2 :(得分:0)

Stored routines

以不同方式调用存储函数和存储过程。

存储函数在SQL语句中用作常规函数。 例如

SELECT id, title,  my_function(price) FROM table

使用CALL语句调用存储过程。

CALL my_procedure(1,2,'title');

我不知道C#,所以可能你可以使用MySqlCommand类来调用存储过程,但你不能用它来调用存储过的函数。

答案 3 :(得分:0)

我实际上无法获得其他建议返回值的方法。我最终创建了一个字符串来调用该函数,然后使用.ExecuteScalar:

执行该字符串
MySqlTransaction mySqlTransaction = testDataMySqlConnection.BeginTransaction();

mySqlCommand = new MySqlCommand
    {
    Connection = testDataMySqlConnection,
    CommandText = "SELECT sf_UnitsAttempted('" + ... + ");",
    CommandType = CommandType.Text
    };

var f = (float)mySqlCommand.ExecuteScalar();
mySqlCommand.Dispose();
return f;

答案 4 :(得分:0)

我知道问题是关于从存储函数返回,Justin的答案在这里涵盖了。我想补充一点,如果您想从存储过程返回DataTable,可以使用DataAdapter

// using MySql.Data.MySqlClient; // remember to include this

/* Helper method that takes in a Dictionary list of parameters, 
   and returns a DataTable. 
   The connection string is fetched from a resources file. */
public static DataTable ExecuteProc(string procedureName, Dictionary<string,object> parameterList)
{
    DataTable outputDataTable;

    using (MySqlConnection MySqlConnection = new MySqlConnection(Resources.SQL_CONNECTION_STRING))
    {
        using (MySqlCommand sqlCommand = new MySqlCommand(procedureName, MySqlConnection))
        {
            sqlCommand.CommandType = CommandType.StoredProcedure;

            if (parameterList != null)
            {
                foreach(string key in parameterList.Keys)
                {
                    string parameterName = key;
                    object parameterValue = parameterList[key];

                    sqlCommand.Parameters.Add(new MySqlParameter(parameterName, parameterValue));
                }
            }

            MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(sqlCommand);
            DataSet outputDataSet = new DataSet();
            sqlDataAdapter.Fill(outputDataSet, "resultset");

            outputDataTable = outputDataSet.Tables["resultset"];
        }
    }

    return outputDataTable;
}