我使用asp.net表单,我有一个select查询并插入查询但是如果我得到select错误消息; "条形码无效&#34 ;;它仍然插入数据库。我不确定如何合并一切;当用户收到错误消息时;不应该插入它,但如果成功则会给它们一个成功的消息。
if (barcode.StartsWith("B"))
{
string Data = " select boxLocation from Box where boxNo= " + barcode.TrimStart('B') + "";
cmd = new SqlCommand(Data, conn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
lblResult.Text = dr[0].ToString();
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
if (barcode.StartsWith("B"))
{
command.CommandText = "insert into Crate_Box (crate_box_no,Current_Location,Previous_Location, Username,Date,status,codeType)values (@crate_box_no,@Current_Location,@Previous_Location, @Username,@Date,@status,@codeType) ";
command.Parameters.Add("@crate_box_no", SqlDbType.NVarChar).Value = barcode.TrimStart('B');
command.Parameters.Add("@Current_Location", SqlDbType.NVarChar).Value = location;
command.Parameters.Add("@Previous_Location", SqlDbType.NVarChar).Value = lblResult.Text;
command.Parameters.Add("@Username", SqlDbType.NVarChar).Value = user;
command.Parameters.Add("@Date", SqlDbType.NVarChar).Value = date;
command.Parameters.Add("@status", SqlDbType.NVarChar).Value = actType;
command.Parameters.Add("@codeType", SqlDbType.NVarChar).Value = "Box";
}
答案 0 :(得分:0)
尝试以下结构:
if (barcode.StartsWith("B"))
{
try
{
// SELECT operation
// INSERT operation
}
catch
{
lblError.Text = barcode + " does not exist!!";
}
finally
{
// Close DB connections and readers
}
}