共用方式為


SqlException.State 屬性

定義

從 SQL Server 取得表示錯誤、警告或「找不到資料」訊息的數值錯誤碼。 如需有關如何將這些值解碼的詳細資訊,請參閱資料庫引擎事件與錯誤

public:
 property System::Byte State { System::Byte get(); };
public byte State { get; }
member this.State : byte
Public ReadOnly Property State As Byte

屬性值

表示錯誤碼的數值。

範例

下列範例會顯示集合內的每一個 SqlErrorSqlErrorCollection

using Microsoft.Data.SqlClient;
using System.Text;

class Program
{
    static void Main()
    {
        string s = GetConnectionString();
        ShowSqlException(s);
        Console.ReadLine();
    }

    public static void ShowSqlException(string connectionString)
    {
        string queryString = "EXECUTE NonExistantStoredProcedure";
        StringBuilder errorMessages = new StringBuilder();

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                for (int i = 0; i < ex.Errors.Count; i++)
                {
                    errorMessages.Append("Index #" + i + "\n" +
                        "Message: " + ex.Errors[i].Message + "\n" +
                        "Error Number: " + ex.Errors[i].Number + "\n" +
                        "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                        "Source: " + ex.Errors[i].Source + "\n" +
                        "Procedure: " + ex.Errors[i].Procedure + "\n");
                }
                Console.WriteLine(errorMessages.ToString());
            }
        }
    }

    static private string GetConnectionString()
    {
        // To avoid storing the connection string in your code, 
        // you can retrieve it from a configuration file.
        return "Data Source=(local);Initial Catalog=AdventureWorks;"
            + "Integrated Security=SSPI";
    }
}

備註

這是 屬性中 Errors 第一個 SqlError 屬性的包裝 State 函式。

如果 為 Errorsnull ,則會 default 傳回 的值 byte

適用於

另請參閱