简体   繁体   中英

Check if User Data is Already in Database

I would like to include functionality within the current code to prevent duplicate additions to be added to the database. This way if someone already registers their name and e-mail, a message instead will pop up to say that they have already added their information to the database. My form is using asp.net the data is populated using c#. Am I able to include something like this: cmd.CommandText = "select * from Table1 where pName='"+t1.Text+"' and pEmail='"+t2.Text+"'"; to achieve that?

c# Code:

using System.Data.OleDb;
using System.Configuration;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ToString();
        con.Open();
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "insert into[Table1](pName)values(@nm)";
        cmd.Parameters.AddWithValue("@nm", TextBox1.Text);
        cmd.CommandText = "insert into[Table1](pEmail)values(@nm)";
        cmd.Parameters.AddWithValue("@nm", TextBox2.Text);
        cmd.Connection = con;
        int a = cmd.ExecuteNonQuery();
        if (a>0)
        {
            Label1.Text = "Inserted Sucessfully!";
        }
    }
}

I would suggest that you have a SELECT query first before INSERT statement. Also you can only use email as parameter on your SELECT statement and not include name since there are chance that persons have the same name.

string query = "SELECT COUNT(ID) FROM tblUsers WHERE email = @email
int count = db.ExecuteReader(query);    


if (count > 0){
   return "email is already in use";
} else {
   //Call the insert statement here with try catch inside. In this way you can handle if error occur on the execution itself.
}

You can use this but I am using SQL server 2014 ..Try this .. Schema

CREATE TABLE [dbo].[Dummy](
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
)

and query

  if not exists(select 1 from Dummy where Name='akash')
  insert into Dummy(Name) values('aka')

This is single query with returns no of row in int a = cmd.ExecuteNonQuery();

Method 2: Create a unique CONSTRAINT and use try catch to found that no duplicate row is inserted..

ALTER TABLE [dbo].[Dummy] ADD  CONSTRAINT [uc_Name] UNIQUE 
NONCLUSTERED 
(
    Name ASC
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM