嗨,我需要在這一個幫助。我想在這裏做的是檢查我的MySQL數據庫,如果一個成員使用基於我的WinForm數據輸入該成員的名稱已經存在。重複錄入工作驗證,顯示在MessageBox完美的方式我想,但它不執行插入查詢我的情況下,毫不現有成員中找到。C#檢查,然後運行插入查詢,如果沒有重複
我是不是做正確嗎?還是有另一種方式讓它按我想要的方式工作。
這裏是我的代碼:
private void metroButton1_Click(object sender, EventArgs e) {
using (con = new MySqlConnection(constring)) {
string selectquery = "SELECT * FROM sbis.sb_members WHERE lname ='" + this.lnametxtbox.Text + "' AND fname = '" + this.fnametxtbox.Text + "' AND mname ='" + this.mnametxtbox.Text + "' ";
MySqlCommand command2 = new MySqlCommand(selectquery, con);
string insertquery = "INSERT INTO sbis.sb_members (lname, fname, mname, position, appointment, address, contactnum, birthdate, civilstatus, educattainment, eligibility, terms_idterms, polparties_id, sex) VALUES (@lname, @fname, @mname, @position, @appointment, @address, @contactnum, @birthdate, @civilstatus, @educattainment, @eligibility, @terms_idterms, @polparties_id, @sex)";
MySqlCommand cmd = new MySqlCommand(insertquery, con);
string lname, fname, mname, address, contactnum, educattainment;
lname = lnametxtbox.Text;
fname = fnametxtbox.Text;
mname = mnametxtbox.Text;
address = addresstxtbox.Text;
contactnum = contacttxtbox.Text;
educattainment = eductxtbox.Text;
var birthdate = birthdatedtp.Value.Date;
cmd.Parameters.AddWithValue("@lname", lname);
cmd.Parameters.AddWithValue("@fname", fname);
cmd.Parameters.AddWithValue("@mname", mname);
cmd.Parameters.AddWithValue("@address", address);
cmd.Parameters.AddWithValue("@contactnum", contactnum);
cmd.Parameters.AddWithValue("@position", position);
cmd.Parameters.AddWithValue("@appointment", appointment);
cmd.Parameters.AddWithValue("@birthdate", birthdate);
cmd.Parameters.AddWithValue("@sex", sex);
cmd.Parameters.AddWithValue("@eligibility", eligibility);
cmd.Parameters.AddWithValue("@civilstatus", civilstatus);
cmd.Parameters.AddWithValue("@terms_idterms", terms);
cmd.Parameters.AddWithValue("@polparties_id", polparties);
cmd.Parameters.AddWithValue("@educattainment", educattainment);
try {
con.Open();
MySqlDataReader cr = command2.ExecuteReader();
while (cr.Read()) {
if (cr.HasRows == true) {
MessageBox.Show("Member already exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
} else if (cr.HasRows == false) {
if (cmd.ExecuteNonQuery() > 0) {
MessageBox.Show("Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
cr.Close();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
感謝您的回覆,我嘗試了INSERT IGNORE,但每次保存時我都會得到重複的條目。 – nolimits
非常感謝您的幫助,非常感謝。 – nolimits
高興已經幫助所有最好與你的項目 – e4c5