如何检查数据库中是否已存在值并显示验证消息 [英] How to check if a value already exists in my database and show a validation message

查看:97
本文介绍了如何检查数据库中是否已存在值并显示验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码连接到Sql数据库并将数据插入表中:

I have the below code, that connects to a Sql database and insert's data into a table :

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文本框中输入的电子邮件,在电子邮件列中,然后发出警报消息说电子邮件已经存在,因此不会插入到我的数据库中?

How do I check if an email being entered in the "txtEmail" text box already exists in my database, in the email column and then alert message saying email already exists so it doesn't get inserted into my database?

推荐答案

调用在所需的文本框或区域中使用此方法

Call this method in required textbox or area

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

    }

这篇关于如何检查数据库中是否已存在值并显示验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆