ASP SQL How to check if username already exists in database table? - c#

I am currently working with SQL database and my assignment is to make a registration form. I have got the registration form to work but I need to check if username have already been taken. In my code Username is in the form of Emails. The code I have works, but as it is, multiple usernames are allowed.
HEre is my code:
protected void registerUser(Object src, EventArgs e)
{
Response.Write("you have connected to your .cs page add records");
get_connection();
try
{
connection.Open();
command = new SqlCommand("INSERT INTO subscribers (FirstName, LastName, Email, Password)" +
" VALUES (#FirstName, #LastName, #Email, #Password)", connection);
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
command.ExecuteNonQuery();
//connection.Close();
}
catch(Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text += "<br /><b>Record has been added</b>";
//lblInfo.Text = "<b>Server Version:</b> " + connection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + connection.State.ToString();
}
}
To check if the username had already been taken, I was thinking about using an "If Then" statement within the "try" area but am unsure what coding I would need. Any help or advice would be appreciated.

You can write something like this:
string cmdText = #"IF NOT EXISTS(SELECT 1 FROM subscribers where Email = #Email)
INSERT INTO subscribers (FirstName, LastName, Email, Password)
VALUES (#FirstName, #LastName, #Email, #Password)"
command = new SqlCommand(cmdText, connection);
......

You can try this code :
string sqlQuery = "IF NOT EXISTS (SELECT 1 FROM subscribers where Email = #Email)
BEGIN
INSERT INTO subscribers (FirstName, LastName, Email, Password) VALUES (#FirstName, #LastName, #Email, #Password)
SELECT SCOPE_IDENTITY()
END
ELSE SELECT 0"
using (command = new SqlCommand())
{
command.CommandText = sqlQuery;
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
connection.Open();
var res = (int)cmd.ExecuteScalar();
connection.Close();
}
if a result is 0 then already exists otherwise new record inserted.

Related

C# Not able to insert records into my database

SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (ParticipantId, LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#ParticipantId, #LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
// cmd.Parameters.AddWithValue("#ParticipantId", notnull);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender.Text);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
cmd.ExecuteNonQuery();
cnn.Close();
I keep getting the error message:
"System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#ParticipantId".' "
I have tried this multiple ways and have been trying to figure this out for a week now. I'm not understanding what is the bug in my code.
Updated version below:
SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
//cmd.Parameters.AddWithValue("#ParticipantId", );
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
int nextKey;
cmd = new SqlCommand("SELECT MAX(ParticipantId) FROM Participant", cnn);
nextKey = (int)cmd.ExecuteScalar() + 1;
// cmd.ExecuteNonQuery();
cnn.Close();
if the column ParticipantId is marked as Identity Then You Should Not Try To Manually Insert data in it , sql server will populate it depending on last used ParticipantId , therefore u should remove the column from the insert statement and remove the id parameter .
if its just a Primary Key then u will need to manually insert unique value for each row .
the error mentioned above is because of the commented line which was supposed to provide a value for ParticipantId parameter

How to prevent duplicate data values from appearing in MySQL Database

I currently have an asp.net website. However I have noticed that in my Registration Page, users are able to register multiple times using the same username. As such, I am wondering if there is a way to prevent the users from registering multiple times using the same username.
I do know that i can set one column in my database to have a primary key... But what do i do if i want to have multiple columns to have primary keys?
This is my Insert Code....
MySqlCommand command = mcon.CreateCommand();
mcon.Open();
command.CommandText = "insert into pointofcontact (FirstName, LastName, EmailAddress, ContactNumber, BackupContactNumber, Address, Gender, Username, Password, Status, ProfilePic) values(?firstname, ?lastname, ?emailaddress, ?contactnumber, ?backupcontactnumber, ?address, ?gender, ?username, ?password, ?status, ?image)";
command.Parameters.AddWithValue("?firstname", firstname);
command.Parameters.AddWithValue("?lastname", lastname);
command.Parameters.AddWithValue("?emailaddress", email);
command.Parameters.AddWithValue("?contactnumber", mobileNumber);
command.Parameters.AddWithValue("?backupcontactnumber", backupNumber);
command.Parameters.AddWithValue("?address", homeAddress);
command.Parameters.AddWithValue("?gender", gender);
command.Parameters.AddWithValue("?username", username);
command.Parameters.AddWithValue("?password", password);
command.Parameters.AddWithValue("?status", status);
command.Parameters.AddWithValue("?image", imageName);
command.ExecuteNonQuery();
mcon.Close();
MySqlDataReader reader = null;
mcon.Open();
MySqlCommand command2 = mcon.CreateCommand();
command2.CommandText = "select * from pointofcontact where Username = ?username";
command2.Parameters.AddWithValue("?username", tbUsername.Text);
reader = command2.ExecuteReader();
if (reader != null && reader.HasRows)
{
lblValidate.Text = "Username already exists.";
}
Response.Redirect("IndexAfterLogin1.aspx");
The data that the user inputs is able to be inserted into my MySQL Database, but the inputted data is able to be repeated for Username and Email fields for different users, and I do not want that to happen.
For that purpose you can add a unique key in table else create a function to check in database before inserting that's it
Make the field username as primary or unique key. It will not allow duplicate entries for that field
Order your code as follows:
try
{
MySqlDataReader reader = null;
mcon.Open();
MySqlCommand command2 = mcon.CreateCommand();
command2.CommandText = "select * from pointofcontact where Username = ?username";
command2.Parameters.AddWithValue("?username", tbUsername.Text);
reader = command2.ExecuteReader();
if (reader != null && reader.HasRows)
{
lblValidate.Text = "Username already exists.";
**return;**
}
else
{
MySqlCommand command = mcon.CreateCommand();
command.CommandText = "insert into pointofcontact (FirstName, LastName, EmailAddress, ContactNumber, BackupContactNumber, Address, Gender, Username, Password, Status, ProfilePic) values(?firstname, ?lastname, ?emailaddress, ?contactnumber, ?backupcontactnumber, ?address, ?gender, ?username, ?password, ?status, ?image)";
command.Parameters.AddWithValue("?firstname", firstname);
command.Parameters.AddWithValue("?lastname", lastname);
command.Parameters.AddWithValue("?emailaddress", email);
command.Parameters.AddWithValue("?contactnumber", mobileNumber);
command.Parameters.AddWithValue("?backupcontactnumber", backupNumber);
command.Parameters.AddWithValue("?address", homeAddress);
command.Parameters.AddWithValue("?gender", gender);
command.Parameters.AddWithValue("?username", username);
command.Parameters.AddWithValue("?password", password);
command.Parameters.AddWithValue("?status", status);
command.Parameters.AddWithValue("?image", imageName);
command.ExecuteNonQuery();
}
}
catch
{
....
}
finally
{
mycon.Close();
}

Full Email Address is not Showing in #Email Column

I have a page for registration where i am saving details of users.
Page is working fine data is shaving but 'full email address' is not showing in table of '#email' column.
Example: if i am saving 'cozm02011#gmail.com' it is showing only 'cozm02011' in table.
code behind
protected void ceratenewuser_Click(object sender, EventArgs e)
{
String ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "User_pro";
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#Password", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#LastSeen", DateTime.Now);
cmd.Parameters.AddWithValue("#CreatedDate", DateTime.Now);
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
Label2.Text = "User Created successfully";
TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4 .Text = "";
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
this.GridView1.DataBind();
}
store procedure
ALTER PROCEDURE dbo.User_pro
#UserName varchar(20),
#Password varchar(20),
#Email varchar(50),
#LastSeen datetime,
#CreatedDate datetime
AS
INSERT INTO User_tbl (UserName, Password, Email, LastSeen, CreatedDate)
VALUES (#UserName, #Password, #Email, #LastSeen, #CreatedDate)
RETURN
You are binding the "Confirm password" field to the E-mail column
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
TextBox3 is used for "Confirm password" field.
Try this,
cmd.Parameters.AddWithValue("#Email", TextBox4.Text.Trim());

Update statement doesn't update my data

I would like to update/edit my user data in Employee table in access database.
When i complete the fields that i want to change (name , last name, etc.), it gives me data updated but when i refresh the table, the data hasn't changed - been updated.
Changes i want to perform for example - Change name from Luke to Taylor, etc.
Where have i gone wrong? Where is the mistake in the code and does my code for adding users to database somehow have influence my update code?
My code for adding users is almost the same as for the update, except for query, and it works fine.
private void button2_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Update Employee set Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #ID";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User updated!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code for adding user data
private void button1_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Insert into Employee (ID, Name, LastName, UserName, Password, E_mail, Address)" + "values (#ID, #Name, #LastName, #UserName, #Password, #E_mail, #Address)";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User added!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for the replies and help
I still have no solution for this. I've tried so many things but i just don't get the right answer.
My current code
try
{
OleDbConnection myConnection = new OleDbConnection("\\DATABASE PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "UPDATE Employees SET Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #";
cmd.Parameters.AddWithValue("#ID", userID.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#LastName", lastName.Text);
cmd.Parameters.AddWithValue("#UserName", userName.Text);
cmd.Parameters.AddWithValue("#Password", pass.Text);
cmd.Parameters.AddWithValue("#E_mail", eMail.Text);
cmd.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("User successfully added.");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Its because your ID in where condition.
You are also changing/updating your ID through:
command.Parameters.AddWithValue("#ID", userID.Text);
This new ID is not found by compiler in Database since you kept where ID=#ID condition in your query.
When you just updates name and other fields then query becomes:
Update Employee set Name = 'Name', LastName = 'LastName', UserName = 'UserName', Password = 'Password', E_mail = 'E_mail', Address = 'Address' WHERE ID = ''";
Your ID might remain blank in that case.
Try the following in your update code:
command.CommandText = "UPDATE Employee SET [Name] = ?, LastName = ?, UserName = ?, [Password] = ?, [E_mail] = ?, Address = ? WHERE [ID] = ?";
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
command.Parameters.AddWithValue("#ID", userID.Text);
The parameters must be in the order in which they appear in the CommandText. This answer was suggested by: Microsoft Access UPDATE command using C# OleDbConnection and Command NOT working
The reasons for this is outlined here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.

Why is my INSERT statement not working for one table?

I have the following INSERT:
public static void insertStudent(int personId, string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode, string majorField, int gradePointAverage)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "INSERT INTO person (personId, firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#personId, #firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("#personId", personId);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
cmd.ExecuteNonQuery();
long id = (long)cmd.LastInsertedId;
sql = "INSERT INTO student (Person_PersonId, majorField , gradePointAverage) VALUES (" + id + ",#majorField, #gradePointAverage";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#majorField", majorField);
cmd.Parameters.AddWithValue("#gradePointAverage", gradePointAverage);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("New student record created created.");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
executed by this button:
private void btnInsertStudentNumberAdmin_Click(object sender, EventArgs e)
{
StudentHelperClass.insertStudent(int.Parse(txtPersonIDStudent.Text), txtFirstNameStudent.Text, txtLastNameStudent.Text, txtDOBStudent.Text, int.Parse(txtPhoneNumberStudent.Text), txtAddressStudent.Text, int.Parse(txtPostCodeStudent.Text), txtMajorFieldStudent.Text, int.Parse(txtGpaStudent.Text));
}
But on the click, I get a message box saying you have an error in your SQL syntax; check the manual that corresponds to your mySql server version for the right version for the right syntax to use near " at line 1 and then my entries for the person table get inserted, but the ones for student do not.
I have made sure that all the ints are int's and all the strings are strings. I'm not sure what the problem is.
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
#majorField,
#gradePointAverage";
is missing a close parentheses. It should be:
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
#majorField,
#gradePointAverage
)";
sql = "INSERT INTO student (Person_PersonId, majorField , gradePointAverage) VALUES (" + id + ",#majorField, #gradePointAverage)";
missing the ending ) ... ?

Categories

Resources