如何停止将重复的用户名添加到数据库 table?

How to stop adding duplicate username into database table?

我正在处理 ASP.Net Web 应用程序项目。在我的注册表中,UsernameEmail 将检查它是否存在于数据库中。但我的问题是如果usernameEmail存在用户可以正常注册并且他的数据将被添加到数据库中!我如何阻止它添加这些数据并强制用户更改 usernameEmail(如果其中之一存在)!请帮忙?

我的 .aspx.cs 页面:

protected void Button1_Click(object sender, EventArgs e)
        {
            byte[] License;
            Stream s = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(s);
            License = br.ReadBytes((Int32)s.Length);
                try
                {
                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
                    conn.Open();
                    string insertQuery = "insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (@name ,@username, @password, @email ,@phone ,@city,@License)";
                    SqlCommand com = new SqlCommand(insertQuery, conn);
                    com.Parameters.AddWithValue("@name", TextBoxName.Text);
                    com.Parameters.AddWithValue("@username", TextBoxUsername.Text);
                    com.Parameters.AddWithValue("@password", TextBoxPassword.Text);
                    com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
                    com.Parameters.AddWithValue("@phone", TextBoxPhone.Text);
                    com.Parameters.AddWithValue("@city", DropDownList1.SelectedItem.ToString());
                    com.Parameters.AddWithValue("@License", License);
                    com.ExecuteNonQuery();
                    Response.Write("DONE");
                    conn.Close();
                }
                catch (Exception ex)
                { Response.Write("Error:" + ex.ToString()); }

        }
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
        { // to check if the Username if exist
            if (!string.IsNullOrEmpty(TextBoxUsername.Text))
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Username=@Username", con);
                cmd.Parameters.AddWithValue("@Username", TextBoxUsername.Text);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    checkusername.Visible = true;
                    imgstatus.ImageUrl = "NotAvailable.jpg";
                    lblStatus.Text = "UserName Already Taken";
                    System.Threading.Thread.Sleep(2000);

                }
                else
                {
                    checkusername.Visible = true;
                    imgstatus.ImageUrl = "Icon_Available.gif";
                    lblStatus.Text = "UserName Available";
                    System.Threading.Thread.Sleep(2000);
                }
            }
            else
            {
                checkusername.Visible = false;
            }

        }

        protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
        { // to check if the Email if exist
            if (!string.IsNullOrEmpty(TextBoxEmail.Text))
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Email=@email", con);
                cmd.Parameters.AddWithValue("@Email", TextBoxEmail.Text);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    Div1.Visible = true;
                    Image1.ImageUrl = "NotAvailable.jpg";
                    Label2.Text = "the Email Already Taken";
                    System.Threading.Thread.Sleep(2000);

                }
                else
                {
                    Div1.Visible = true;
                    Image1.ImageUrl = "Icon_Available.gif";
                    Label2.Text = "the Email Available";
                    System.Threading.Thread.Sleep(2000);
                }
            }
            else
            {
                Div1.Visible = false;
            }
        }

对您的用户名和电子邮件列设置唯一约束,您的 sql 插入将抛出异常,您可以处理该异常并相应地通知客户。

https://msdn.microsoft.com/en-GB/library/ms190024.aspx

需要在数据库中设置主键。

假设 'username' 是您的主键,因此是唯一的。然后你可以检查它是否已经存在于数据库中,如下所示:

private void button2_Click(object sender, EventArgs e
{
   conn.Open();
   com.Connection = conn;

   sql = "SELECT COUNT(*) FROM lapusers WHERE [username] = @username";
   com.CommandText = sql;
   com.Parameters.Clear();
   com.Parameters.AddWithValue("@username", userlapbox.Text);
   int numRecords = (int)com.ExecuteScalar();

   if (numrecords == 0)
   {
      sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(@username,@fillingcode,@branch,@department,@agency)";
      com.CommandText = sql;
      com.Parameters.Clear();
      com.Parameters.AddWithValue("@username", userlapbox.Text);
      com.Parameters.AddWithValue("@fillingcode", userfilllapbox.Text);
      com.Parameters.AddWithValue("@branch", comboBox2.Text);
      com.Parameters.AddWithValue("@department", comboBox1.Text);
      com.Parameters.AddWithValue("@agency", comboBox3.Text);
      com.ExecuteNonQuery();
      MessageBox.Show("Created Successfully ..");      
   }
   else
   {
      MessageBox.Show("A record with a user name of {0} already exists", userlapbox.Text);
   }

   conn.Close();
}

使用插入存储过程而不是内联插入查询,并在插入之前的存储过程中检查此用户名电子邮件 ID 是否存在。

if (not exists(select 1 from DeliveryMen where Username= @Username and Email=@Email))
begin
insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (@name ,@username, @password, @email ,@phone ,@city,@License)
end