奇怪的MySqlException:超时已过期

时间:2014-06-09 10:12:48

标签: c# mysql

我有一个奇怪的问题。我有一个程序,如果应用程序捕获异常,它会向我发送一封电子邮件。通过这些异常处理,我的应用程序将向用户显示一个消息框,表明存在错误。但我的问题是,我的用户从未从应用程序中收到错误消息,但我总是收到一封电子邮件,该程序捕获了异常。为了向您展示,这是我的MySqlClass,用于处理程序的sql事务:

    /// <summary>
    /// Disposable class to handle database transactions
    /// Error logging use can be found in TechSol_Skeet => Error.cs
    /// </summary>
    public class DbHelper : IDisposable
    {
        #region Properties 

        //public properties need to be set before opening the connection
        public bool UseStored = false;
        public bool UseTransaction = false;
        public string ConnectionString { get; set; }
        public string Query { get; set; }

        private MySqlConnection _connection { get; set; }
        private MySqlCommand _command { get; set; }
        private MySqlTransaction _transaction;

        #endregion

        public DbHelper()
        {
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                if (_command != null) _command.Dispose();
                if (_connection != null) _connection.Dispose();
                if (_transaction != null) _transaction.Dispose();
            }

            Query = null;
            ConnectionString = null;

        }

        ~DbHelper()
        {
            Dispose(false);
        }

        #endregion IDisposable Members

        /// <summary>
        /// Opens the connection, make sure to set the public properties before calling this out
        /// If uses transaction, BeginTransaction
        /// </summary>
        public void Open()
        {
            try
            {
                _connection = new MySqlConnection(ConnectionString);
                _connection.Open();

                if (UseTransaction)
                {
                    _transaction = _connection.BeginTransaction();
                }

                _command = new MySqlCommand
                {
                    Connection = _connection,
                    CommandType = UseStored ? CommandType.StoredProcedure : CommandType.Text,
                    CommandText = Query
                };
            }
            catch(MySqlException ex)
            {
                Error.SendToDeveloper("DbHelper.Open()", ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// use in select statements
        /// </summary>
        public DataTable GetData(MySqlParameter[] parameters)
        {
            var result = new DataTable();

            try
            {
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        _command.Parameters.Add(param);
                    }
                }

                using (var dataAdapter = new MySqlDataAdapter(_command))
                {
                    dataAdapter.Fill(result);
                }
            }
            catch(MySqlException ex)
            {
                Error.SendToDeveloper("DbHelper.GetData()", ex.ToString());
                throw;
            }

            return result;
        }

        /// <summary>
        /// use in create, update and insert statements
        /// </summary>
        public int ExecuteNonQuery(MySqlParameter[] parameters)
        {
            int result = 0;
            try
            {
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        _command.Parameters.Add(param);
                    }
                }

                result = _command.ExecuteNonQuery();
            }
            catch(MySqlException ex)
            {
                Error.SendToDeveloper("DbHelper.ExecuteNonQuery", ex.ToString());
                throw;
            }

            return result;
        }

        /// <summary>
        /// use in commiting transactions
        /// </summary>
        public void Commit()
        {
            try
            {
                _transaction.Commit();                
            }
            catch (MySqlException ex)
            {
                Error.SendToDeveloper("DbHelper.Commit", ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// use in rolling back transactions
        /// </summary>
        public void RollBack()
        {
            try
            {
                _transaction.Rollback();
            }
            catch (MySqlException ex)
            {
                Error.SendToDeveloper("DbHelper.RollBack", ex.ToString());
                throw;
            }
        }
    }

以下是我通过电子邮件收到的例外情况:

MySql.Data.MySqlClient.MySqlException (0x80004005): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.TimeoutException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
  at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
  at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
  --- End of inner exception stack trace ---
  at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
  at MySql.Data.Common.MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  --- End of inner exception stack trace ---
  at MySql.Data.Common.MyNetworkStream.HandleOrRethrowException(Exception e)
  at MySql.Data.Common.MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at MySql.Data.MySqlClient.TimedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
  at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
  at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
  at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
  at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
  at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
  at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
  at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
  at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
  at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
  at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
  at MySql.Data.MySqlClient.MySqlConnection.HandleTimeoutOrThreadAbort(Exception ex)
  at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
  at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
  at MySql.Data.MySqlClient.Driver.LoadServerProperties(MySqlConnection connection)
  at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection)
  at MySql.Data.MySqlClient.MySqlConnection.Open()
  at TechSol.DbHelper.Open()

以下是该类的示例用法,如果出现问题,将显示错误消息:

try
{
    using (var db = new DbHelper())
    {
        db.ConnectionString = _connString;
        db.Query = "InsertTransaction";
        db.UseStored = true;
        db.Open();

        db.ExecuteNonQuery();
    }
}
catch(MySqlException mySex)
{
    string message = string.Format("{0} \r\n\r\n Please try again! \r\n\r\n Please contact developer", mySex.Message);
    MessageBox.Show(message, "Error");
}

我希望我能为此明确提出问题。非常感谢!

- 编辑 -

这是静态错误类:

public static class Error
{
    public static void SendToDeveloper(string location, string body)
    {
        using (var message = new MailMessage())
        {
            message.To.Add(ConfigurationManager.AppSettings["dev_mail"]);
            message.From = new MailAddress(ConfigurationManager.AppSettings["email_sender"]);
            message.Subject = string.Format("Error in {0}, {1}, {2}",
                                            ConfigurationManager.AppSettings["application_name"], location,
                                            DateTime.Now);
            message.Body = body;

            try
            {
                var smtp = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
                smtp.Send(message);
            }
            catch (SmtpException sex)
            {
                SendToDeveloper("Error.SMTPCLIENT", sex.ToString());
                throw;
            }
        }
    }
}

这是连接字符串:

<add name="conn_string" connectionString="Server=server;uid=user;Database=database;Pwd=pass;Convert Zero Datetime=True;"
     xdt:Transform="Replace" xdt:Locator="Match(name)"/>

0 个答案:

没有答案