Home > Back-end >  How to check for duplicated Name before adding it to the database
How to check for duplicated Name before adding it to the database

Time:10-11

Create to check for the duplicated name before being entered in the database)

private void btn_Submit_Click(object sender, EventArgs e)
{
    con.Open();

    SqlCommand cmd = con.CreateCommand();

    if (txt_Name.Text == "Employee")
    {
        cmd.ExecuteNonQuery();
        con.Close();

        display_data();
        MessageBox.Show("Name existed");
    }
    else
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into Employee values('"   txt_Name.Text   "','"   txt_Contact.Text   "','"   txt_Address.Text   "','"   txt_Email.Text   "','"   txt_Password.Text   "')";

        cmd.ExecuteNonQuery();

        con.Close();

        display_data();
        MessageBox.Show("Inserted successfully");
    }
}

CodePudding user response:

It is a security risk to concat the string with the parameters, use the sqlcommand parameters instead https://learn.microsoft.com/de-de/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=dotnet-plat-ext-6.0

Example:

var query = "INSERT INTO Employee VALUES (@name, @contact, @address, @email, @password)";
cmd.CommandText = query;

cmd.Parameters.AddWithValue("@name", txt_Name.Text);
cmd.Parameters.AddWithValue("@contact", txt_Contact.Text);
cmd.Parameters.AddWithValue("@address", txt_Address.Text);
cmd.Parameters.AddWithValue("@email", txt_Email.Text);
cmd.Parameters.AddWithValue("@password", txt_Password.Text);

There are several ways to the goal for your problem

IF NOT EXISTS (SELECT * FROM Employee WHERE Name = @name)
BEGIN
    INSERT INTO Employee VALUES (@name, @contact, @address, @email, @password)
END

CodePudding user response:

You can get the number of rows with the same name. If it is greater than zero, do not add new row... But the better way is to create a UNIQUE INDEX for the name column in sql like:

CREATE UNIQUE INDEX uidx_pid
ON Employee(name);

then on c# code:

        string sqlQuery = "insert into Employee values('"   txt_Name.Text   "','"   txt_Contact.Text   "','"   txt_Address.Text   "','"   txt_Email.Text   "','"   txt_Password.Text   "')";
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(sqlQuery , con))
            {
                try
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                    display_data();
                    MessageBox.Show("Inserted successfully");
                }
                catch(Exception ex) {
                    display_data();
                    MessageBox.Show("Name existed");
                };
                
            }
        }
  • Related