Can't make check if user already exists in my database - c#

I started to learn ASP.NET. I create a register system, and when I try to check if the username or email already exists in the database, it's not checked and creates the user even when you have it already.
try
{
conn.Open();
bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" + username.Text + "'";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);
exists = (int)cmd2.ExecuteScalar() > 0;
if (exists)
{
Response.Write("User already exists");
}
string command = "INSERT INTO accounts (username, email, password) VALUES (#username, #email, #password)";
SqlCommand cmd = new SqlCommand(command, conn);
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
cmd.ExecuteNonQuery();
}
catch(Exception)
{
label_msg.Visible = true;
label_msg.Text = "Something went wrong....";
throw;
}
finally
{
Response.Redirect("/layout.aspx");
conn.Close();
}
Thanks !

string checkuser = "if exists (select 1 from accounts where username=#username) select 1 else select 0 end";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("#username", username.Text);
bool exists = (int)cmd2.ExecuteScalar() > 0;
Having SQL Server check for the existence of matches will stop at the first match instead of potentially returning a set of matches and then it is simply returning a value accordingly. This will minimize data transferred between the server and your software plus avoid performing a count when we really just care if there are any matches.

whenever you want to find TRUE/FALSE value or counting the no records always use COUNT(1).

bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username=#username;";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("#username", username.Text);
object result = cmd2.ExecuteScalar();
if (result != null)
exists = (Convert.ToInt32(result) == 1) ? true : exists;
if (exists)
{
Response.Write("User already exists");
}

Check if user Exist already
int exists = 0;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" +username.Text + "'";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);
exists = (int)cmd2.ExecuteScalar();
if (exists>0)
{
Response.Write("User already exists");
}

Related

Password not resetting on a database through an ASP.Net application

I am trying to reset a password to an employee number on a database through a ASP.Net application. The trouble is that it is not actually resetting the password on DB even though I am getting a confirmation message that the password has been reset.
Here is my current code
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
string empNo = "";
empNo = txtEmpNo.Text;
empReset = txtEmpNo.Text;
// sql statement to check if employee number exists in DB
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM tbl_Login WHERE (Emp_ID = #user)", sqlcon);
check_User_Name.Parameters.AddWithValue("#user", empNo);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//EmpNo exists
sqlCmd = new SqlCommand("update tbl_Login set Emp_Pass=#Pass where Emp_ID=#EmpID", sqlcon);
sqlCmd.Parameters.AddWithValue("#EmpID", empNo);
sqlCmd.Parameters.AddWithValue("#Pass", "1234");
lblExists.Text = "Password reset!";
}// end if
else
{
//EmpNo doesnt exist
lblExists.Text = "Employee doesnt exists";
}//end else
you need to execute your second statement in the if:
if (UserExist > 0)
{
//EmpNo exists
sqlCmd = new SqlCommand("update tbl_Login set Emp_Pass=#Pass where Emp_ID=#EmpID", sqlcon);
sqlCmd.Parameters.AddWithValue("#EmpID", empNo);
sqlCmd.Parameters.AddWithValue("#Pass", "1234");
sqlCmd.ExecuteNonQuery(); // <- execute update
lblExists.Text = "Password reset!";
}// e
you missed
sqlCmd.ExecuteNonQuery();

Check if user exists in SQL Server user table

I am trying to make a registration form. This code should stop the registration if there is a duplicate of username.
I actually copied this on this answer tried to modify it on my own so I could somehow learn how it works.
Here is my code:
private void register_user()
{
con.Open();
bool exist = false;
// Command that checks if username exist
cmd = new SqlCommand(#"SELECT COUNT(*) FROM users1 WHERE Username = '#username'", con);
cmd.Parameters.AddWithValue("#username", txtRegUsername.Text);
exist = (int)cmd.ExecuteScalar() > 0;
// If user exist gives error
if (exist == true)
lblResults.Text = "Username already exist!";
else
{
cmd = new SqlCommand(#"INSERT INTO users1 (Fname, Lname, Mname,
Username, Password, email, user_type)
VALUES (#first_name, #last_name, #middle_name,
#username, #password, #email, #user_type)", con);
cmd.Parameters.AddWithValue("#first_name", txtFname.Text);
cmd.Parameters.AddWithValue("#last_name", txtLname.Text);
cmd.Parameters.AddWithValue("#middle_name", txtMi.Text);
cmd.Parameters.AddWithValue("#username", txtRegUsername.Text);
cmd.Parameters.AddWithValue("#password", txtRegPassword.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#user_type", "user");
cmd.ExecuteNonQuery();
}
con.Close();
}
My problem is that my code allows the registration of Username which already exist. Overall its working.
Instead of
SELECT COUNT(*) FROM users1 WHERE Username = '#username'
use
SELECT COUNT(*) FROM users1 WHERE Username = #username
Otherwise that's not a parameter but a static value for Username.
Side note: I would not count records if I want to know if something exists.
This is more efficient:
SELECT
CASE WHEN EXISTS(SELECT 1 FROM users1 WHERE Username = #username)
THEN 1
ELSE 0
END AS DoesUserExist
Try the below code.. Hope this will help you.
cmd = new SqlCommand(#"SELECT COUNT(*) FROM users1 WHERE upper(Username) = upper(#username)", con);
exist is false then you return the value of the SelectCount.
I would do something as
If((int)cmd.ExecuteScalar() > 0)
{
exist=true;
}
Also remove the ' ' from #username on the query as others said.

How to check if SQL database already has the entered Username?

I've written this registration form which adds data to my SQL Server database. What I want is an exception when the user enters a username that is already in the database.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn2.Open();
string CheckUser = "select Username from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
com2.ExecuteNonQuery();
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
conn2.Close();
if (IsMatch == 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string InsertQuery = "insert into UserData (Username, Email, Password, Country) values (#Username, #Email, #Password, #Country)";
SqlCommand com = new SqlCommand(InsertQuery, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
conn.Close();
}
else
{
Response.Write("User Already Exists!");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex));
}
}
When I run it, I get an exception on the following line:
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
Blam's second solution works, but the IsMatch can be simplified a bit by casting to int instead of going to string and parsing.
This should also be handled at the database level. Set a primary key on your username column:
ALTER TABLE UserData ADD CONSTRAINT
PK_UserData PRIMARY KEY CLUSTERED (Username)
If you do it this way, then you don't even have to check for duplicates explicitly, you can just try to create the user and handle the exception if it fails:
try
{
using (var conn = new SqlConnection((ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)))
{
conn.Open();
#if DOUBLE_CHECK
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
if ((int)com2.ExecuteScalar() > 0)
{
Response.Write("User already exists");
return;
}
#endif
string InsertQuerry = "insert into UserData (Username,Email,Password,Country) values (#Username,#Email,#Password,#Country)";
SqlCommand com = new SqlCommand(InsertQuerry, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
}
}
catch (SqlException se)
{
if (se.Errors.OfType<SqlError>().Any(e => e.Number == 2627))
{
Response.Write("User already exists");
}
else
{
Response.Write(se.ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
If you handle the exception this way, the #if DOUBLE_CHECK section is redundant and can be removed. An attempt to add duplicate name will cause a SQL error and exception, and this will detect and handle the "duplicate key" error.
Two unrelated notes on your code:
Response.Redirect() will abort the current thread and your conn.Close() will not be called. Use a using() to ensure it's called.
Storing a password in the database as plain text is a disaster waiting to happen. PLEASE take a look at Best way to store password in database for some ideas about how to do this correctly
That won't return an integer
string CheckUser = "select count(*) from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
And you don't need to use two different connections.
Just use one and close it in a Finally.
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text );
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
This returns 0 or 1. This should fix your issue. Looks like you need to return an int type. Or you could change it to bool if you want. Either way, this sql statement should help! :)
select
isnull(convert(bit,(select top 1 case
when username != '' then 1
else 0 end
from UserData
where username like #Username)),0)

How to check if a value already exists in my database and show a validation message

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();
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;
}
}
}
Try this
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";
Call a stored Procedure and inside the stored procedure you can check
before insert
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =#email)
Begin
insert query here
end
In another way you can check it in text changed event also
Create a procedure on SQL server and check whether the name exists or not
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
This is a sample procedure. If #isExist=1 that means the value exist.otherwise not. create a method to call this procedure and go on...
Happy Coding
This works for me:
Create a function Called CheckMail(string email)
public bool CheckMail(string email)
{
SqlConnection con = new SqlConnection("Data Source=*******; Initial Catalog=Your Database Name; Persist Security Info=True;User ID=****; Password=******");
SqlCommand cmd = new SqlCommand("select email from Table Name where email='"+email+ "'",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
return false;
}
else
{
return true;
}
}
Then Implement in Button Click as
Pass Textbox value in function that were created..
if (CheckMail(EmailTxt.Text))
{
Write Your insert code to database
}
else
{
Error Message or Alert to Show Already Exists in database
}

How to check if record exists or not and insert in ms access database in c#

I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#.
OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);
temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("One Record Added");
}
else
{
MessageBox.Show("Record not added");
}
}
catch
{ }
Can Anyone suggest me some code.
Thanks In Advance.
Filter your Select query on the basis of some key . Check if it returns for existence or non-existence of the particular record and do the processing required .
string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
int count = (int)cmd.ExecuteScalar();
if(count >0)
{
//record already exist
}
Modify this line
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);

Categories