我已尝试过以下代码,但它会抛出一个唯一的键约束错误。我希望它是一个弹出式消息;见下面的代码。
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
var fromdate = DateTime.Parse(txtfromdate.Text);
var todate = DateTime.Parse(txttodate.Text);
var datedif1 = (todate - fromdate).Days;
var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth]) VALUES (@datedif,@batch,@daywk,@semester,@weekbatch,@subject,@facultyname,@facultyid,@weekMonth)", con2);
var sqlParamater = sqlInsert.Parameters.Add("@datedif", SqlDbType.Date);
var sqlParameter1 = sqlInsert.Parameters.Add("@batch", SqlDbType.NVarChar);
var sqlParameter2 = sqlInsert.Parameters.Add("@daywk", SqlDbType.NVarChar);
var sqlParameter3 = sqlInsert.Parameters.Add("@semester", SqlDbType.NVarChar);
var sqlParameter4 = sqlInsert.Parameters.Add("@weekbatch", SqlDbType.NVarChar);
var sqlParameter5 = sqlInsert.Parameters.Add("@subject", SqlDbType.NVarChar);
var sqlParameter6 = sqlInsert.Parameters.Add("@facultyname", SqlDbType.NVarChar);
var sqlParameter7 = sqlInsert.Parameters.Add("@facultyid", SqlDbType.NVarChar);
var sqlParameter8 = sqlInsert.Parameters.Add("@WeekMonth", SqlDbType.NVarChar);
con2.Open();
try
{
for (var i = 0; i <= datedif1; i++)
{
var consecutiveDate = fromdate.AddDays(i);
sqlParamater.Value = consecutiveDate;
sqlParameter1.Value = batch1;
sqlParameter2.Value = dayweek;
sqlParameter3.Value = semester;
sqlParameter4.Value = weekbatch;
sqlParameter5.Value = subject;
sqlParameter6.Value = faculty;
sqlParameter7.Value = facultyid;
sqlParameter8.Value = weekmonth;
int s = sqlInsert.ExecuteNonQuery();
}
con2.Close();
}
catch(ConstraintException ex)
{
throw new ApplicationException("data are duplicated");
}
}
以下是错误的屏幕截图,
答案 0 :(得分:1)
您正在捕获ConstraintException
,但插入的是SqlException
,它不是ConstraintException
的子类。改变捕获量,你将得到它。