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

时间:2015-07-30 13:01:41

标签: c# sql asp.net registration

我正在使用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;
            }
        }

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:3)

使用插入存储过程而不是内联插入查询,并在插入检查之前在存储过程中使用此用户名电子邮件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

答案 2 :(得分:2)

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

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

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();
}