MysqlCommand ExecuteNonquery返回值始终为0

时间:2015-12-16 17:51:52

标签: mysql c#-4.0 visual-studio-2013

我试图验证mysql何时执行非查询,它应该返回受影响的行。然而,当我使用存储过程时,它总是返回0。

注意:此代码是通用的,用于执行任何存储过程,并在必要时返回存储过程的输出值。

C#:

    /// <summary>
    /// Execute the query to mysql DB and returns all the OUT values by the DB..
    /// </summary>
    /// <param name="strStoredProcedureName">Name of the stored procedure to execute</param>
    /// <param name="parameters">list that contains all the IN parameters name with their respectif values</param>
    /// <param name="outParameters">list that contains all the OUT parameters name with their My SQL DB types</param>
    /// <param name="lstOfOutValues">List that contains the OUT parameter name and the value that the DB returned.</param>
    /// <returns>True, executed successfully</returns>
    public static bool Execute(string strStoredProcedureName, Dictionary<string, object> parameters, Dictionary<string, MySqlDbType> outParameters, out Dictionary<string, object> lstOfOutValues)
    {
        bool blnIsExecuted = true;
        MySqlCommand cmd = null;
        int rowsAffected = 0;
        Dictionary<string, object> lstOfValues = null;
        string strParameterName = string.Empty;

        try
        {
            using (dbMain = DB.OpenConnection())
            {
                cmd = new MySqlCommand(strStoredProcedureName, dbMain);
                cmd.CommandType = CommandType.StoredProcedure;

                // IN paramters
                foreach (KeyValuePair<string, object> item in parameters)
                {
                    strParameterName = string.Format("?{0}", item.Key);
                    cmd.Parameters.Add(new MySqlParameter(strParameterName, item.Value));
                    cmd.Parameters[strParameterName].Direction = ParameterDirection.Input;
                }

                // OUT paramters
                foreach (KeyValuePair<string, MySqlDbType> item in outParameters)
                {
                    strParameterName = string.Format("?{0}", item.Key);
                    cmd.Parameters.Add(new MySqlParameter(strParameterName, item.Value));
                    cmd.Parameters[strParameterName].Direction = ParameterDirection.Output;
                }

                rowsAffected = cmd.ExecuteNonQuery(); // Execute the query
                blnIsExecuted = rowsAffected > 0 ? true : false;

                if (blnIsExecuted)
                {
                    lstOfValues = new Dictionary<string, object>();

                    // Create the list of values from the out paramters array.
                    foreach (KeyValuePair<string, MySqlDbType> item in outParameters)
                    {
                        strParameterName = string.Format("?{0}", item.Key);
                        lstOfValues.Add(item.Key, cmd.Parameters[strParameterName].Value);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            blnIsExecuted = false;
            lstOfValues = null;
            System.Windows.MessageBox.Show(string.Format("Class : [DB]"
                                                         + "\nMethod : Execute(string strStoredProcedureName, Dictionary<string, object> parameters, Dictionary<string, MySqlDbType> outParameters, out Dictionary<string, object> lstOfOutValues)"
                                                         + "\n\nError : {0}", ex.Message), "ERROR");
        }

        lstOfOutValues = lstOfValues;
        return blnIsExecuted;
    }

存储过程:

# DECLARATIONS OF VARIABLES
DECLARE Test TINYINT(1) DEFAULT false;
DECLARE varDocumentID INT(11) DEFAULT 0;
DECLARE varFileName VARCHAR(255) DEFAULT '';
DECLARE varQuery LONGTEXT DEFAULT '';

# ROLLBACK if there's any SQL Exception or Warning error with the Insert of the Transactions
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING
BEGIN
    SELECT false AS Result;
    ROLLBACK;
END;

SET varQuery = CONCAT('INSERT INTO order_document_reception'
                      , '\r', 'SET OrderType = \'', argOrderType, '\''
                      , '\r', ', Status = \'O\''
                      , '\r', ', Priority = ', argPriority
                      , '\r', ', ClientID = \'', argClientID, '\''
                      , '\r', ', BillingID = \'', argBillingID, '\''
                      , '\r', ', ShippingID = \'', argShippingID, '\''
                      , CASE WHEN argModelID != '' THEN CONCAT('\r', ', ModelID = \'', argModelID, '\'') ELSE '' END
                      , CASE WHEN argDiscountID != '' THEN CONCAT('\r', ', DiscountID = \'', argDiscountID, '\'') ELSE '' END
                      , '\r', ', PurchaseOrderNumber = \'', argPurchaseOrderNo, '\''
                      , '\r', ', DocumentFileName = \'', argOrderType, '\''
                      , '\r', ', DocumentReceivedDate = \'', argDocumentReceiveDate, '\''
                      , CASE WHEN argDocumentReceptionType != -1 THEN CONCAT('\r', ', DocumentReceptionType = ', argDocumentReceptionType) ELSE '' END
                      , '\r', ', DocumentReceivedBy = \'', argDocumentReceivedBy, '\''
                      , CASE WHEN argTherapist != '' THEN CONCAT('\r', ', Therapist = \'', argTherapist, '\'') ELSE '' END
                      , CASE WHEN argPurchaser != '' THEN CONCAT('\r', ', Purchaser = \'', argPurchaser, '\'') ELSE '' END
                      , CASE WHEN argUser != '' THEN CONCAT('\r', ', User = \'', argUser, '\'') ELSE '' END
                      , CASE WHEN argClientWO != '' THEN CONCAT('\r', ', ClientWorkOrderNumber = \'', argClientWO, '\'') ELSE '' END
                      , '\r', ', CreatedDate = \'', NOW(), '\'');
IF Test THEN
    SELECT varQuery;
ELSE
    START TRANSACTION;
        SET @Qry = varQuery;
        PREPARE Statement FROM @Qry;
        EXECUTE Statement;
        DEALLOCATE PREPARE Statement;

        # FETCH THE LAST INSERT ID OF THE DOCUMENT TO CREATE THE FILE NAME.
        SET varDocumentID = LAST_INSERT_ID();
        SET varFileName = CONCAT(argOrderType, '_', CONVERT(varDocumentID, CHAR(50)), '.pdf');

        # UPDATE THE DOCUMENT NAME
        UPDATE order_document_reception SET DocumentFileName = varFileName WHERE (ID = varDocumentID);

        # SET THE argDocumentID PARAMETER TO THE DOCUMENT ID VARIABLES THAT WAS USED TO CREATE THE ORDER DOCUMENT.
        SELECT varDocumentID INTO argDocumentID;
        SELECT varFileName INTO argFileName;
    COMMIT;

    SELECT true AS Result;
END IF;

当我直接从Mysql中选择但我的rowsAffected变量始终为0时,我看到插入已成功完成,为什么?

1 个答案:

答案 0 :(得分:0)

我认为,因为你将你的插入作为SP中的执行字符串间接完成,而不是原始形式。

我在工作台上写了一个快速的ST测试..一个间接调用类似于你拥有的

CREATE DEFINER=`root`@`localhost` PROCEDURE `tester`()
BEGIN


DECLARE varQuery LONGTEXT DEFAULT '';

SET varQuery = CONCAT('INSERT INTO therinks.glreturndata '
                  , '\r', 'SET glaccount = \'', 'test', '\'');


 SET @Qry = varQuery;
    PREPARE Statement FROM @Qry;
    EXECUTE Statement;
    DEALLOCATE PREPARE Statement;


END

当通过工作台运行时..它会返回0行影响..即使它已插入

然后我使用了直接插入..就像这样:

CREATE DEFINER=`root`@`localhost` PROCEDURE `tester`()
BEGIN



INSERT INTO therinks.glreturndata SET glaccount = 'test';



END

在工作台上运行时,它会正确报告1行有效。

我会尝试测试并将insert语句隐藏在String后面,看看该测试是否首先返回正确的行数。