当我输入已经存在的数据时,为什么我的数据库逻辑没有抛出异常?

Why isn't my database logic throwing an exception when I enter data that already exists?

我有一个链接到数据库的小型 ASP.NET 注册页面。如果用户输入数据库中已经存在的用户名,那么它应该显示 "user already exists",但它并没有这样做:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if(IsPostBack)
        {
            SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();

            string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";

            SqlCommand comm = new SqlCommand(check, conn);

            int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
            if (temp == 1)
            {
                Response.Write("User already exists!!");

            }
            conn.Close();
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
        {
            Response.Write("Select Country and age!");
        }
        else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
        {
            Response.Write("Select Country!");
        }
        else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
        {
            Response.Write("Select Age!");
        }
        else
        {
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
                conn.Open();
                string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
                SqlCommand comm = new SqlCommand(insertQ, conn);
                comm.ExecuteNonQuery();
                Response.Redirect("Display.aspx");

                conn.Close();
            }
            catch(Exception ex)
            {
                Response.Write("Error : " + ex.ToString());
            }
        }
    }
}

我觉得你应该先试试

 If ( temp > 0)
    {
    }

同时调试以查看 sql 查询

返回的内容

几件事。

  1. 您需要在插入数据之前检查此项。
  2. 如果用户名仍然存在,您不会阻止输入相同的数据
  3. 您可以检查前 1 个而不是计数。

    private bool IsUserExists()
    { 
      bool UserExists = false;
      SqlConnection conn =new    SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
    
            string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
    
            SqlCommand comm = new SqlCommand(check, conn);
    
            int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
            if (temp >= 1)
            {
                UserExists = true;
                Response.Write("User already exists!!");
    
            }
            conn.Close();
      }
     return UserExists ;
      }
    

插入数据前检查此项。

  try
        {  
           if(UserExists())
             return;  //Skips further code when user exists.


            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
            SqlCommand comm = new SqlCommand(insertQ, conn);
            comm.ExecuteNonQuery();
            Response.Redirect("Display.aspx");

            conn.Close();
        }
        catch(Exception ex)
        {
            Response.Write("Error : " + ex.ToString());
        }