簡體   English   中英

如何避免mysql數據庫中的重復

[英]how to avoid duplication in mysql database

當我插入 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

我不確定避免重復是什么意思,但是如果您的意思是避免插入相同的數據,那么您可以考慮將INSERT包裝在存儲過程中,您可以在其中檢查這些數據是否存在,例如

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#代碼中調用此過程,傳遞當前傳遞的所有參數。

很好,它有效:))

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM