简体   繁体   中英

how to avoid duplication in mysql database

when i insert in mysql data base, i would like to avoid the duplication. what should i add in the "if" expression. the insert function is :

private void Inscrire_Click(object sender, EventArgs e)
    { //bouton insert

        cmd = new MySqlCommand("INSERT INTO users (Matricule,mot_de_passe,Nom,Prenom) VALUES(@Matricule,@mot_de_passe,@Nom,@Prenom)", con);

            cmd.Parameters.AddWithValue("@Matricule", textBox1.Text);
            cmd.Parameters.AddWithValue("@mot_de_passe", textBox2.Text);
            cmd.Parameters.AddWithValue("@Nom", textBox3.Text);
            cmd.Parameters.AddWithValue("@Prenom", textBox4.Text);


            MySqlDataReader dr;
            // avoiding duplication of "Matricule"
            // what can i add here?
                if (textBox1.Text.Equals(""))
                {
                    MessageBox.Show("existe déja");
                }
                else
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("inscription réussite !");
                    Form1 f = new Form1();
                    f.ShowDialog();
                }

    }

French to English

Matricule - Id #
motte de passe - password
Nom - surname
prénom - firstname

I am not absolutely sure what you mean by avoiding duplication but if you mean to avoid inserting the same data then you can consider wrapping your INSERT in a stored procedure where you can check for existence of those data like

create procedure usp_testInsert (@Matricule varchar(10),
              @mot_de_passe varchar(10),
              @Nom varchar(10) ,
              @Prenom varchar(10))
as
begin
INSERT INTO users (Matricule,mot_de_passe,Nom,Prenom) 
SELECT @Matricule,
@mot_de_passe,
@Nom,
@Prenom
WHERE NOT EXISTS (SELECT 1 FROM users 
WHERE Matricule = @Matricule AND mot_de_passe = @mot_de_passe
AND Nom = @Nom AND Prenom = @Prenom);
end

You can then call this procedure in your C# code passing all the parameter what you are passing currently.

很好,它有效:))

create procedure usp_testInsert(Matricule int, mot_de_passe varchar(10), Nom varchar(10) , Prenom varchar(10)) begin INSERT INTO users (Matricule,mot_de_passe,Nom,Prenom) SELECT @Matricule, @mot_de_passe, @Nom, @Prenom FROM users WHERE NOT EXISTS (SELECT 1 FROM users WHERE Matricule = @Matricule AND mot_de_passe = @mot_de_passe AND Nom = @Nom AND Prenom = @Prenom ); end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM