如何避免在mysql数据库中重复

时间:2015-06-24 23:33:45

标签: c# mysql database insert duplication

当我插入mysql数据库时,我想避免重复。我应该在“if”表达式中添加什么。 插入功能是:

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

    }

法语到英语

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

2 个答案:

答案 0 :(得分:1)

我不能完全确定你的意思是避免重复,但是如果你想避免插入相同的数据,那么你可以考虑将INSERT包装在一个存储过程中,你可以在那里检查是否存在这些数据。 / p>

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

然后,您可以在C#代码中调用此过程,并传递当前传递的所有参数。

答案 1 :(得分:0)

好,它有效:))

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 
相关问题