Asking for legitimate example of calling stored procedure C#: MYSQL

前端 未结 2 946
既然无缘
既然无缘 2020-11-30 15:27

I\'ve spent about 7 hours trying to figure this out by trial and error. All the online examples I have seen either don\'t work, or dont apply, or only show half of what Im l

相关标签:
2条回答
  • 2020-11-30 16:07

    I believe the code and the pictures say more than I ever will.

    C# DB Layer (DB Layer has conn as a connection string):

    // Note: this is an instance (myDB in terms of the GUI Object)
    
    using System.Data;
    using MySql.Data.MySqlClient;
    ...
    ...
    public long MultBySeven(long theNum)
    {   // Call a Mysql Stored Proc named "multBy7"
        // which takes an IN parameter, Out parameter (the names are important. Match them)
        // Multiply the IN by 7 and return the product thru the OUT parameter
    
        long lParam = 0;
        using (MySqlConnection lconn = new MySqlConnection(connString))
        {
            lconn.Open();
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = lconn;
                cmd.CommandText = "multBy7"; // The name of the Stored Proc
                cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
    
                // Two parameters below. An IN and an OUT (myNum and theProduct, respectively)
                cmd.Parameters.AddWithValue("@myNum", theNum); // lazy, not specifying ParameterDirection.Input;
                cmd.Parameters.AddWithValue("@theProduct", MySqlDbType.Int32);
                cmd.Parameters["@theProduct"].Direction = ParameterDirection.Output; // from System.Data
                cmd.ExecuteNonQuery(); // let it rip
                Object obj = cmd.Parameters["@theProduct"].Value;
                lParam = (Int32)obj;    // more useful datatype
            }
        }
        return (lParam);
    }
    

    C# GUI Test Layer:

    private void btnTestInOut_Click(object sender, EventArgs e)
    {   // This GUI Layer call thru the use of a business object or data layer object (`myDB`)
        long localHere = myDB.MultBySeven(11);
    }
    

    Stored Procedure (take a number, multiply by 7):

    DROP PROCEDURE IF EXISTS multBy7;
    DELIMITER $
    CREATE PROCEDURE multBy7
    (   IN myNum INT,
        OUT theProduct INT
    )
    BEGIN
        SET theProduct=myNum*7;
    END$
    DELIMITER ;
    

    Debug View (read: it works. 11x7=77):

    MySQL Connector 6.9.9.0 / Visual Studio 2015:

    See also 5.10.1 Using Stored Routines from Connector/Net, age unknown.

    0 讨论(0)
  • 2020-11-30 16:11

    You should set up a reference to the parameter

    var param3 = new MySqlParameter();
    param3.Direction = ParameterDirection.Output;
    param3.DbType = // whatever the dbtype for int is or whatever you need.
    param3.ParameterName = "param3";
    
    com.Parameters.Add(param3);
    

    in your try block, insert

    var result = com.ExecuteReader(); // or com.ExecuteScalar();
    

    after you execute that, your parameter should have the value populated and you should be able to also read the SP results (select).

    var paramResult = param3.Value;
    

    Reading the results of the SP can be done as reader or scalar.

    // execute reader
    while (result.Read()) {
        int value = result.GetInt32(0)); 
    } /* read returned values in result */ 
    
    // execute scalar
    int value;
    if (int.TryParse($"{result}", out value)) {
        /* do something with value */ 
    }
    

    /************************************************/

    This block should get you where you need to go

            const string strcon = "whatevs";
    
            using (MySqlConnection con = new MySqlConnection(strcon))
            {
                const string sql = "login";
    
                MySqlCommand com = new MySqlCommand(sql, con);
                com.CommandType = CommandType.StoredProcedure;
    
                var stuffParam = new MySqlParameter("stuff", stuffValue);
                var passParam = new MySqlParameter("pass", passValue);
                var param3Param = new MySqlParameter();
                param3Param.ParameterName = "param3";
                param3Param.DbType = DbType.Int32;
                param3Param.Direction = ParameterDirection.Output;
    
                com.Parameters.Add(stuffParam);
                com.Parameters.Add(passParam);
                com.Parameters.Add(param3Param);
    
                try
                {
                    var scalarResult = com.ExecuteScalar();
    
                    // because you used select @param3 in your sp.
                    int value;
                    if (int.TryParse($"{scalarResult}", out value))
                    {
                        //do something with value
                    }
    
                    //// because you used select @param3 in your sp.
                    //var readerResult = com.ExecuteReader();
    
                    //if (readerResult.Read())
                    //{
                    //    // 
                    //    value = readerResult.GetInt32(0);
                    //}
    
                    int param3Returned;
                    if(int.TryParse($"{param3Param.Value}", out param3Returned))
                    {
                        // do something with param3Returned
                    }
                }
                catch (Exception ex)
                {
                    // do something with ex
                }
            }
    
    0 讨论(0)
提交回复
热议问题