SQL异常不在消息框中显示

时间:2018-10-08 12:52:55

标签: c# sql messagebox

尝试插入重复项时出现SQL异常,但SQL错误未发送到消息框。我可以在调试中看到错误。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using static AccountManager.productinsert.BusinessLogic;

namespace AccountManager
{
  public partial class ProductAdd : Form
  {
    public ProductAdd()
    {
      InitializeComponent();
    }

    public void CleartextBoxes1()
    {
      ProductId.Clear();
      ProductName.Clear();            
      ProductPrice.Clear();
    }

    private void BtnClose_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void BtnSubmit_Click(object sender, EventArgs e)
    {
      try
      {
        var product = new ProductDetails();
        product.ProductId = ProductId.Text;
        product.ProductName = ProductName.Text;
        product.ProductPrice = ProductPrice.Text;
        AddProduct(product);

        MessageBox.Show("Product Created!");
        CleartextBoxes1();
      }
      catch (SqlException)
      {
          MessageBox.Show("Product Already Exists");
      }
    }
  }
}

调试产生的错误是

  

Exception捕获到的异常:“ System.Data.SqlClient.SqlException”   AccountManager.exe(“违反UNIQUE KEY约束   'UQ__产品__B40CC6CC7010A856'。无法在其中插入重复的密钥   对象“ dbo.Products”。重复键值为(1)。该声明   已终止。“)System.Data.SqlClient.SqlException

根据要求添加产品的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace AccountManager
{
    class productinsert
    {

        public class BusinessLogic
        {
            public static void AddProduct(ProductDetails details)
            {
                using (SqlConnection openCon = new SqlConnection("Data Source=.;Initial Catalog=AccountMGR;Integrated Security=True;"))
                {
                    var statement = "insert into Products(" +
                           "  ProductId, ProductName, Price)" +
                           " values(" +
                           "  @ProductId," +
                           "  @ProductName," +
                           "  @Price)";



                    using (SqlCommand queryInsert = new SqlCommand(statement))
                    {
                        queryInsert.Connection = openCon;

                        queryInsert.Parameters.Add("@ProductId", SqlDbType.VarChar, 30).Value = details.ProductId;
                        queryInsert.Parameters.Add("@ProductName", SqlDbType.VarChar, 30).Value = details.ProductName;
                        queryInsert.Parameters.Add("@Price", SqlDbType.VarChar, 30).Value = details.ProductPrice;



                        openCon.Open();
                        try
                        {
                            queryInsert.ExecuteNonQuery();
                        }
                        catch (SqlException)
                        {

                        }
                    }
                }


            }




            public class ProductDetails
            {

                public string ProductId { get; set; } = "";
                public string ProductName { get; set; } = "";
                public string ProductPrice { get; set; } = "";


            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

尝试一下

try
{
     SaveData();
}
catch (Exception ex)
{
     var sqlException = ex.InnerException as System.Data.SqlClient.SqlException;

     if (sqlException.Number == 2601)
     {
         MessageBox.show("Product Already Exists");
     }
     else
     {
         MessageBox.show(ex.Message());
     }
}

2627是唯一约束错误

2601用于重复的键行错误

希望这对您有帮助!

答案 1 :(得分:1)

您应该在常规SqlException之前赶上Exception。并定义您的SqlException的对象实例,下面的代码可以解决您的问题:

try
{
    queryInsert.ExecuteNonQuery();
}
catch (SqlException e)
{

    if (exc.Number == 2601)
    {
        MessageBox.show("Your Record is already exists");
    }
    else
    {
        MessageBox.show(e.Message());
    }
}
catch(Exception e)
{
    // other kind of exception
}

注释:

  

2601表示重复的键行错误

     

2627表示唯一约束错误

答案 2 :(得分:1)

如果您已使用try catch,则应抛出异常以进行捕获

try
{
    queryInsert.ExecuteNonQuery();
}
catch 
{
   throw;
}
相关问题