如何使用连接层在C#应用程序中获取存储过程错误

时间:2019-05-20 12:27:12

标签: c# sql sql-server

我有一个用于插入数据库的存储过程,其中包含异常处理和我想在C#中捕获的错误。整个执行过程进展顺利,但是当我插入错误的语句并希望出现错误时,我不知道如何将错误中的消息打印到C#应用程序的消息框中。

这是我的存储过程:

CREATE PROCEDURE spNewBooking
( 
   @customer VARCHAR(255), 
   @incheckdate DATE,
   @checkoutdate DATE,
   @hotel VARCHAR(40),
   @count_persons INT,
   @emplyeeid INT,
   @roomid int
) 
AS 
BEGIN 
    DECLARE @bookdate DATE = GETDATE() 

    IF NOT EXISTS(SELECT name
                  FROM customer
                  WHERE @customer = name)   
    BEGIN 
        RAISERROR ('This customer does not exists', 16, 1)
        RETURN
    END 

    BEGIN TRANSACTION
        SELECT @customer = customerid
        FROM customer
        WHERE @customerid = name

        SELECT @hotel = hotelid
        FROM hotel
        WHERE @hotel = location

        INSERT INTO booking 
        VALUES (@bookdate, @count_persons, NULL, @customer, @hotel, @emplyeeid)

        INSERT INTO boekingroom 
        VALUES (@roomid, @incheckdate, @checkoutdate, NULL, NULL)

        IF @@ERROR <> 0
        BEGIN
            ROLLBACK
            RAISERROR ('Error! Check the input', 16, 1)
            RETURN
        END

        COMMIT
END

在我的应用程序中,我有一个类Database,其中有用于插入的方法。我从主窗口获取参数,执行在主窗口中进行。

这是主窗口的代码:

private void BtnBook_Click_1(object sender, RoutedEventArgs e)
{
        try
        {
            Database.AddBooking(textBoxcustomer.Text, Convert.ToDateTime(dpIncheck.Text), Convert.ToDateTime(dpCheckout.Text), dpHotellocation.Text, Convert.ToInt32(dpCountpersons.Text), 2, 7);
            MessageBox.Show("Done!!");
        }
        catch (SqlException E)
        {
            MessageBox.Show(E.Message);
        }
}

数据库类中的代码

public static void Addbooking(string klant, DateTime incheck, DateTime uitcheck, string hotel, int aantal_personen, int medewerker, int kamerid)
{
    using (SqlConnection connection = new SqlConnection(ConnectionString))
    {
        connection.Open();
        string query = "exec spNewBooking '" + customer + "', '" + incheck + "', '" + checkout + "', '" + hotel + "', '" + countperson + "', '" + employeeid + "', '" + kamerid +"'";

        SqlCommand selectNieuweAuditCommand = new SqlCommand(query, connection);

        SqlDataReader myreader;
        myreader = selectNewBookingCommand.ExecuteReader();

        while (myreader.Read())
        { }
    }
}

如何在C#应用程序的消息框中获取存储过程中的错误?

1 个答案:

答案 0 :(得分:0)

您可以返回状态代码,而不是从存储过程中返回空值。

 IF @@ERROR <> 0
        BEGIN
            ROLLBACK
            RAISERROR ('Error! Check the input', 16, 1)
            RETURN @@ERROR
        END

您还可以将SP添加到DataContext并将其用作具有整数返回数据类型的DataContext的常规方法