Click here to Skip to main content
14,326,236 members
Rate this:
Please Sign up or sign in to vote.
See more:
Issue With Connection When Working With SSMS.

How to Check EmailId Exist in the database or not?

<pre><pre>
        protected void Button1_Click(object sender, EventArgs e)
        {
            string firstname = txtFirstName.Text;
            string lastname = txtLastName.Text;
            string emailid = txtEmailId.Text;
            string password = txtclientpassword.Text;
            Registration_Click(firstname, lastname, emailid, password);
        }

 void Registration_Click(string firstname,string lastname,string emailid,string Password)
        {
            string conn = ConfigurationManager.ConnectionStrings["connstr"].ToString();
            SqlConnection cn = new SqlConnection(conn);

            cn.Open();

            string Insertquery = "Insert into tbladminclient(FirstName,LastName,EmailId,Password) values(@FirstName,@LastName,@EmailId,@Password)";
            SqlCommand cmd = new SqlCommand(Insertquery, cn);
            cmd.CommandType = CommandType.Text;

            string query = "SELECT * FROM tbladminclient WHERE EmailId='" + txtEmailId.Text + "'";
            cmd.Parameters.AddWithValue(query, cn);
            int count = (int)cmd.ExecuteScalar();

            if (count > 0)
            {
                Label2.Text = "EmailId is Already In Use";
            }

            cmd.Parameters.AddWithValue("@FirstName", firstname);
            cmd.Parameters.AddWithValue("@LastName", lastname);
            cmd.Parameters.AddWithValue("@EmailId", emailid);
            cmd.Parameters.AddWithValue("@Password", Password);

            try
            {
                int validateOperation = cmd.ExecuteNonQuery();
                if (validateOperation > 0)
                {
                    Response.Write("successfully Registration");
                    Response.Redirect("ClientLogin.aspx");
                }
                else
                {
                    Response.Write("Not successfully Registration");
                }
            }
            catch (SqlException e)
            {
                Response.Write("error");
            }
            finally
            {
                cn.Close();
            }
        }
    }


How to Identify Emailid is existed in the database or not??



Image:
Error:
<a href="https://imgur.com/a/hzILnC1">Imgur: The magic of the Internet</a>[<a href="https://imgur.com/a/hzILnC1" target="_blank" title="New Window">^</a>]


What I have tried:

I want the Emailid is already is inserted in the database then not inserted the second time?
Posted
Updated 8-Oct-19 9:41am
Rate this:
Please Sign up or sign in to vote.

Solution 1

For starters, don't do it like that! Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

And remember: if this is web based and you have any European Union users then GDPR applies and that means you need to handle passwords as sensitive data and stored them in a safe and secure manner. Text is neither of those and the fines can be .... um ... outstanding. In December 2018 a German company received a relatively low fine of €20,000 for just that.

And did you try looking at your code?
cn.Open();
...
string query = "SELECT * FROM tbladminclient WHERE EmailId='" + txtEmailId.Text + "'";
cmd.Parameters.AddWithValue(query, cn);
Why are you trying to use the SQL query as a parameter name, and the connection instance as a parameter?


[edit]
And definitely don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
DROP TABLE MyTable;
A perfectly valid "delete the table" command
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
You clearly know what a parameterised query is - or you believe that "development" is the same as "copy'n'paste'n'hopeItWorks" - so use them. Always!
[/edit]
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

OK, so we have a few problems going on here...

SQL Vulnerability and Poor Password practices, which have been covered in Original Griff's answer[^], and I am not going to rehash these points.

Code organization- you have a pretty good building of the INSERT statement, and then there is a SELECT statement right in the middle; almost looks like those lines were dragged in or copy and pasted.

Your variables are inconsistent between those two SQL statements; further suggesting a haphazard copy/paste of code.

You have two SQL objects that are not properly disposed and an unutilized Exception object

The Select statement is going to return all rows matching that email address, and you are calling this via ExecuteScalar() which will grab the value from row[0]-column[0] and then attempting to make this an INT. If the result is null or anything other than numeric you are going to have issues.
Best thing to do here would be to edit the SELECT command.

Now what I would do would be similar to this; I would probably work on the feedback to the user (Label2.text vs Response.Write) but that is on you
void Registration_Click(string firstname,string lastname,string emailid,string Password) {
	string conn =        // leave as is
	string InsertQuery = // leave as is
	string SelectQuery = "SELECT Count(*) FROM tblAdminClient WHERE EmailId = @EmailID"; // Get the count of matching records, will always return a number if query is valid

	using (SqlConnection cn = new SqlConnection(cn)) {
		using (SqlCommand cmd = new SqlCommand(SelectQuery, cn)) {
			cmd.CommandType  = CommandType.Text;
			cmd.Parameters.AddWithValue (emailid);

			conn.Open();

			int count = (int)cmd.ExecuteScalar();

			if (count > 0) { Label2.Text = "EmailId is Already In Use"; }
			else {								// only insert if record wasnt found
				cmd.CommandText = InsertQuery;
				
				cmd.Parameters.AddWithValue("@FirstName", firstname);
				cmd.Parameters.AddWithValue("@LastName", lastname);
			//	cmd.Parameters.AddWithValue("@EmailId", emailid); 	/* not needed, already in command parameter collection */
				cmd.Parameters.AddWithValue("@Password", Password);

				try {
					int validateOperation = cmd.ExecuteNonQuery();
					if (validateOperation > 0) {
						Response.Write("successfully Registration");
						Response.Redirect("ClientLogin.aspx");
					}
					else { Response.Write("Not successfully Registration"); }
				}

				catch (SqlException e) { Response.Write("ERROR: " + e.Message"); } // might as well say what the error was, or don't declare "e"

				// cn.Close not needed with USING block
				// AND would not 
				// finally { cn.Close(); }
			}
		}
	}
}
   
Comments
Member 14613437 5 days ago
   
@MadMyche thanks for the suggestion thanks again.
MadMyche 5 days ago
   
Looks like I forgot to put that name in; the line should be
cmd.Parameters.AddWithValue("@EmailId", emailid);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100