我有以下代码,它连接到Sql数据库并将数据插入表中:
string firstNameV = txtFname.Text;
string surnameV = txtSname.Text;
string emailV = txtEmail.Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (@Title,@FirstName,@Surname,@Email,@EstablishmentType,@Interests)";
cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = title;
cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = firstNameV;
cmd.Parameters.Add("@Surname", SqlDbType.NVarChar).Value = surnameV;
cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = emailV;
cmd.Parameters.Add("@EstablishmentType", SqlDbType.NVarChar).Value = eType;
cmd.Parameters.Add("@Interests", SqlDbType.NVarChar).Value = ins;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
如何检查是否在" txtEmail"中输入了电子邮件?文本框已经存在于我的数据库中,在电子邮件列中,然后是警告消息,说电子邮件已经存在,因此它不会插入到我的数据库中?
答案 0 :(得分:6)
在必需的文本框或区域中调用此方法
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= @EmailId", con);
cmd.Parameters.AddWithValue("@EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
答案 1 :(得分:0)
试试这个
cmd.CommandText = "IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email = '"
+ txtEmail.Text + "')
BEGIN
INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (@Title,@FirstName,@Surname,@Email,@EstablishmentType,@Interests)
END";
答案 2 :(得分:0)
调用存储过程并在存储过程内部进行检查 在插入之前
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =@email)
Begin
insert query here
end
另一方面,您可以在文本更改事件中检查
答案 3 :(得分:0)
在SQL Server上创建一个过程并检查名称是否存在
CREATE PROCEDURE Procedure_Name
@mystring varchar(100),
@isExist bit out
AS
BEGIN
if exists(select column1 from tblTable1 where column1=@mystring)
begin
select @isExist=1
end
else
begin
select @isExist=0
end
END
GO
这是一个示例程序。如果@ isExist = 1表示该值存在,则表示不存在。创建一个方法来调用此过程并继续... 快乐编码