当前位置: 首页>>代码示例>>C#>>正文


C# SqlClient.SqlException类代码示例

本文整理汇总了C#中System.Data.SqlClient.SqlException的典型用法代码示例。如果您正苦于以下问题:C# SqlException类的具体用法?C# SqlException怎么用?C# SqlException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SqlException类属于System.Data.SqlClient命名空间,在下文中一共展示了SqlException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddExceptToError

 /// <summary>
 /// Adds the given SqlException's message to the general error logger.
 /// </summary>
 /// <param name="except">The sql exception storing the message that gets passed to the logger</param>
 protected void AddExceptToError(SqlException except)
 {
     if (except.Number == -2 || except.Number == 0)
     {
         GeneralLogger.GetInstance().AddError(except.Message);
     }
 }
开发者ID:Wailord,项目名称:TimeDefender,代码行数:11,代码来源:DatabaseController.cs

示例2: ParseSQLException

        private static string[] ParseSQLException(SqlException ex)
        {
            string errField, errMessage;

            switch (ex.Number)
            {
                case 2601:
                case 2627:
                    {
                        char[] splited = { '"', '“', '”' };
                        string[] msg = ex.Message.Split(splited);
                        if (msg.Length <= 2)
                        {
                            errField = null;
                            errMessage = ex.Message;
                        }
                        else
                        {
                            errField = msg[1];
                            errMessage = string.Format("Value of '{0}' exists, can not insert the same value.", errField);
                        }
                    }
                    break;
                default:
                    {
                        errField = null;
                        errMessage = ex.Message;
                    }
                    break;
            }

            return new string[2] { errField, errMessage };
        }
开发者ID:zhanxp,项目名称:enuocms,代码行数:33,代码来源:ExceptionHelper.cs

示例3: GetSqlErrorMessage

        /// <summary>
        /// Получить текст сообщения для исключения БД
        /// </summary>
        /// <param name="exception">Исключение БД</param>
        /// <returns>Текст сообщения</returns>
        private static string GetSqlErrorMessage(SqlException exception)
        {
            string result = Resources.SqlMessages.UnknownError;
            int errorCode = exception.Number;

            switch (errorCode)
            {
                case 2601:
                    // Duplicate key
                    result = Resources.SqlMessages.DuplicateRecord;
                    break;
                case 547:
                    // Reference/Foreign key constraint conflict
                    var match = Regex.Matches(exception.Message, @"The (\w+) .+")[0];
                    string operation = match.Groups[1].Value;
                    if (operation == "INSERT" || operation == "UPDATE")
                    {
                        result = Resources.SqlMessages.ConstraintConflict;
                    }
                    else if (operation == "DELETE")
                    {
                        result = Resources.SqlMessages.DeleteErrorConstraint;
                    }
                    break;
                case 8152:
                    // String or binary data would be truncated
                    result = Resources.SqlMessages.TooLongString;
                    break;
            }

            return result;
        }
开发者ID:hash2000,项目名称:WorkTime,代码行数:37,代码来源:ErrorMessageHelper.cs

示例4: CheckExp

        public static string CheckExp(SqlException ex)
        {
            switch (ex.Number)
            {
                case 2627:
                    return "Already Exist ...";
                case 233:
                    return "Sql Server Is Not Running ...";
                case 2:
                    return "Sql Server Is Not Running ...";
                case 515:
                    string ReturnMe = "You Must Fill" + Environment.NewLine;
                    int tempint = 0;
                    foreach (char Chr in ex.Message.ToCharArray())
                    {
                        //Get column name from error msg and its between ''
                        char Dot = '\'';

                        if (Chr == Dot)
                            tempint++;
                        if (tempint == 1)
                            ReturnMe += Chr;
                        else if (tempint == 2)
                            break;
                    }
                    return ReturnMe + "'";
                default:
                    return ex.Message;
            }
        }
开发者ID:EgyFalseX,项目名称:Winform,代码行数:30,代码来源:MCls.cs

示例5: CheckExp

        public static string CheckExp(SqlException ex)
        {
            switch (ex.Number)
            {
                case 2627:
                    return "موجود مسبقا";
                case 515:
                    string ReturnMe = "يجب مليء " + Environment.NewLine;
                    int tempint = 0;
                    foreach (char Chr in ex.Message.ToCharArray())
                    {
                        //Get column name from error msg and its between ''
                        char Dot = '\'';

                        if (Chr == Dot)
                            tempint++;
                        if (tempint == 1)
                            ReturnMe += Chr;
                        else if (tempint == 2)
                            break;
                    }
                    return ReturnMe + "'";
                case 241:
                    return String.Format("خطاء في نوع البيان {0}من فضلك فحص الارقام و التواريخ", Environment.NewLine);
                case 242:
                    return String.Format("خطاء في ادخال التاريخ {0}من فضلك تأكد ان صياغة التاريخ هي {0}سنه/شهر/يوم", Environment.NewLine);
                default:
                    return ex.Message;
            }
        }
开发者ID:EgyFalseX,项目名称:Winform,代码行数:30,代码来源:Program.cs

示例6: CheckExp

    public static string CheckExp(SqlException ex)
    {
        switch (ex.Number)
        {
            case 2627:
                return "موجود مسبقاً ...";
            case 233:
                return "SQl Server غير متاح";
            case 2:
                return "SQl Server غير متاح";
            case 515:
                string ReturnMe = "يجب مليء" + Environment.NewLine;
                int tempint = 0;
                foreach (char Chr in ex.Message.ToCharArray())
                {
                    //Get column name from error msg and its between ''
                    char Dot = '\'';

                    if (Chr == Dot)
                        tempint++;
                    if (tempint == 1)
                        ReturnMe += Chr;
                    else if (tempint == 2)
                        break;
                }
                return ReturnMe + "'";
            default:
                return "خطاء في بيانات الادخال";
        }
    }
开发者ID:EgyFalseX,项目名称:WebSites,代码行数:30,代码来源:mcRetirementWeb.cs

示例7: TranslateSQLException

        /// <summary>
        ///   function to translate sql exceptions to readable messages. 
        ///   It also captures cases where sql server is not available and guards against
        ///   database connection details being leaked
        /// </summary>
        /// <param name = "exc"></param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        public static string TranslateSQLException(SqlException exc)
        {
            int i = 0;
            var errorMessages = new StringBuilder();
            for (i = 0; i <= exc.Errors.Count - 1; i++)
            {
                SqlError sqlError = exc.Errors[i];
                string filteredMessage = string.Empty;
                switch (sqlError.Number)
                {
                    case 17:
                        filteredMessage = "Sql server does not exist or access denied";
                        break;
                    case 4060:
                        filteredMessage = "Invalid Database";
                        break;
                    case 18456:
                        filteredMessage = "Sql login failed";
                        break;
                    case 1205:
                        filteredMessage = "Sql deadlock victim";
                        break;
                    default:
                        filteredMessage = exc.ToString();
                        break;
                }

                errorMessages.Append("<b>Index #:</b> " + i + "<br/>" + "<b>Source:</b> " + sqlError.Source + "<br/>" + "<b>Class:</b> " + sqlError.Class + "<br/>" + "<b>Number:</b> " +
                                     sqlError.Number + "<br/>" + "<b>Procedure:</b> " + sqlError.Procedure + "<br/>" + "<b>Message:</b> " + filteredMessage + "<br/>");
            }
            return errorMessages.ToString();
        }
开发者ID:rut5949,项目名称:Dnn.Platform,代码行数:41,代码来源:SqlUtils.cs

示例8: HandleForeignKey

 private DbException HandleForeignKey(string message, SqlException exception)
 {
     var result = new DbException(message, exception)
     {
         IsForeignKeyViolation = true
     };
     return result;
 }
开发者ID:marinoscar,项目名称:Luval,代码行数:8,代码来源:SqlServerExceptionHandler.cs

示例9: LogSqlException

 public static void LogSqlException(SqlException ex, ILog log)
 {
     log.ErrorFormat("Server: {0}, Procedure:{1} Number:{2} Message:{3}", ex.Server, ex.Procedure, ex.Number, ex.Message);
     foreach (SqlError item in ex.Errors)
     {
         log.ErrorFormat("State: {0}, Procedure: {1}, Number: {2}, LineNumber: {3}, Message:{4}", item.State, item.Procedure, item.Number, item.LineNumber, item.Message);
     }
 }
开发者ID:chuckfrazier,项目名称:DataPlatform,代码行数:8,代码来源:LoggerHelper.cs

示例10: ThrowQueueNotFoundException

        static void ThrowQueueNotFoundException(Address destination, SqlException ex)
        {
            var msg = destination == null
                ? "Failed to send message. Target address is null."
                : string.Format("Failed to send message to address: [{0}]", destination);

            throw new QueueNotFoundException(destination, msg, ex);
        }
开发者ID:adamralph,项目名称:NServiceBus.SqlServer,代码行数:8,代码来源:SqlServerMessageSender.cs

示例11: SqlExecutionException

 public SqlExecutionException(string message, string server, string database, string sqlFile, string commands, SqlException sqlException) : base(message)
 {
     this._server = server;
     this._database = database;
     this._sqlFile = sqlFile;
     this._commands = commands;
     this._sqlException = sqlException;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:SqlExecutionException.cs

示例12: SqlExecutionException

 private SqlExecutionException(SerializationInfo info, StreamingContext context)
    :base(info, context) {
    _server = info.GetString("_server");
    _database = info.GetString("_database");
    _sqlFile = info.GetString("_sqlFile");
    _commands = info.GetString("_commands");
    _sqlException = (SqlException)info.GetValue("_sqlException", typeof(SqlException));
 }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:8,代码来源:SqlServices.cs

示例13: Convert

        /// <summary>
        ///     Converts the specified sqle.
        /// </summary>
        /// <param name="sqle">The sqle.</param>
        /// <param name="exInfo">The ex info.</param>
        /// <returns>Exception thrown by NHibernate</returns>
        private System.Exception Convert(SqlException sqle, AdoExceptionContextInfo exInfo)
        {
            System.Exception finalException;
            if (sqle != null)
            {
                switch (sqle.Number)
                {
                    case 17:
                    // SQL Server does not exist or access denied. 
                    case 4060:
                    // Invalid Database 
                    case 18456:
                        // Login Failed 
                        finalException = new DbLoginException(sqle.Message, sqle);
                        break;

                    case 1205:
                        // DeadLock Victim 
                        finalException =
                            new DbDeadLockException(sqle.Message, sqle);
                        break;

                    case 2627:
                    case 2601:
                        // Unique Index/Constriant Violation 
                        finalException =
                            new DbUniqueConstraintException(sqle.Message, sqle);
                        break;
                    case 547:
                        finalException =
                            new DbForeignKeyException(sqle.Message, sqle);
                        break;

                    case 208:
                        finalException =
                            new SQLGrammarException(
                                exInfo.Message, sqle.InnerException, exInfo.Sql);
                        break;

                    case 3960: // in case of snapshot isolation
                        finalException =
                            new StaleObjectStateException(exInfo.EntityName, exInfo.EntityId);
                        break;

                    default:
                        finalException =
                            SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message,
                                exInfo.Sql);
                        break;
                }
            }
            else
            {
                finalException = SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message,
                    exInfo.Sql);
            }
            return finalException;
        }
开发者ID:phucls,项目名称:ara,代码行数:64,代码来源:SQLServerExceptionConverter.cs

示例14: checkUniqueViolationException

 public static bool checkUniqueViolationException(String mensaje, SqlException Ex)
 {
     if (Ex.Number == 2627)
     {
         MessageBox.Show(mensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return true;
     }
     return false;
 }
开发者ID:juanmjacobs,项目名称:gestion2c2013,代码行数:9,代码来源:SQL.cs

示例15: ReexecuteCommand

 public static bool ReexecuteCommand(SqlException sqlException, ref SqlCommand command) {
     if (SqlExceptionsThatCauseRederivingSqlCommand.Values.Contains(sqlException.Number)) {
         command = CommandMethods.RederiveCommand(command);
         if (command != null) {
             return true;
         }
     }
     return false;
 }
开发者ID:DNCarroll,项目名称:Weapons,代码行数:9,代码来源:SqlExceptionsThatCauseRederivingSqlCommand.cs


注:本文中的System.Data.SqlClient.SqlException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。