如果我尝试将Employee提交到数据库中已存在电子邮件地址的数据库,我想抛出消息框让用户知道该问题,否则让数据为保存。
下面是我目前的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Employees
{
public partial class Registration : Form
{
SqlConnection con;
SqlCommand com;
SqlDataReader sdr;
string cmdstr;
string constr = @"Data Source=DESKTOP-J6KRI77\SQLEXPRESS; Initial Catalog = SELLnBUY; Integrated Security=true";
public Registration()
{
InitializeComponent();
}
private void btnsubmit_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
cmdstr = "INSERT INTO Emptbl([First Name], [Last Name], sex, [Birth Date], Email, Password, Confirm_Password, Membership) VALUES(@fname, @lname, @sex, @dob, @email, @password, @confirmpassword, @membership)";
con.Open();
com = new SqlCommand(cmdstr, con);
if (txtfname.Text == "" || txtlname.Text == "" || combosex.SelectedItem.ToString() == "" || maskeddob.Text == "" || txtemail.Text == "" || txtpassword.Text == "" || txtconfirmpassword.Text == "" || (!radiopremium.Checked && !radioregular.Checked))
{
MessageBox.Show("Please, fill all the fields");
}
else
{
com.Parameters.AddWithValue("@fname", txtfname.Text);
com.Parameters.AddWithValue("@lname", txtlname.Text);
com.Parameters.AddWithValue("@sex", combosex.SelectedItem.ToString());
com.Parameters.AddWithValue("@dob", maskeddob.Text);
com.Parameters.AddWithValue("@email", txtemail.Text);
com.Parameters.AddWithValue("@password", txtpassword.Text);
com.Parameters.AddWithValue("@confirmpassword", txtconfirmpassword.Text);
if (radiopremium.Checked)
{
com.Parameters.AddWithValue("@membership", "Premium");
}
else
{
com.Parameters.AddWithValue("@membership", "Regular");
}
com.ExecuteNonQuery();
MessageBox.Show("Thanks for registering");
txtfname.Clear();
txtlname.Clear();
combosex.Text = "";
maskeddob.Clear();
txtemail.Clear();
txtpassword.Clear();
txtconfirmpassword.Clear();
grpbxmembership.Text = "";
txtfname.Focus();
}
con.Close();
}
答案 0 :(得分:0)
首先,你的代码很老了。现在所有人都使用ORM。
然后,关于您的问题,您只需在插入数据库之前检查数据库是否存在相同的数据。
SqlCommand command = new SqlCommand("select count(*) from Emptbl where Email= @email");
command.Parameters.AddWithValue("@email", txtemail.Text);
var count= (Int32)cmd.ExecuteScalar();
if(count>0)
//Show error