Update statement doesn't update my data - c#

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.

Related

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

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.

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());

fatal error encountered during command execution during update

i use this code to update data that are in the textboxes... this code is in the update button and once i made the changes and clicked the button the error message appears
try
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_info SET SEM = #SEM, STUDENT_NO = #STUDENT_NO, LASTNAME = #LASTNAME" +
", FIRSTNAME = #FIRSTNAME, MIDDLENAME = #MIDDLENAME, CITY = #CITY, STREET = #STREET, GENDER = #GENDER" +
", COURSE = #COURSE, YEAR = #YEAR, SECTION = #SECTION, BIRTHDAY = #BIRTHDAY Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#SEM", sem_combo.Text);
cmd.Parameters.AddWithValue("#STUDENT_NO", studentNo_txt.Text);
cmd.Parameters.AddWithValue("#LASTNAME", lname_txt.Text);
cmd.Parameters.AddWithValue("#FIRSTNAME", fname_txt.Text);
cmd.Parameters.AddWithValue("#MIDDLENAME", mname_txt.Text);
cmd.Parameters.AddWithValue("#CITY", address_txt.Text);
cmd.Parameters.AddWithValue("#STREET", street_txt.Text);
cmd.Parameters.AddWithValue("#GENDER", gender_combo.Text);
cmd.Parameters.AddWithValue("#COURSE", program_combo.Text);
cmd.Parameters.AddWithValue("#YEAR", yr_combo.Text);
cmd.Parameters.AddWithValue("#SECTION", section_combo.Text);
cmd.Parameters.AddWithValue("#BIRTHDAY", bday.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL, CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Check in This Line
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
Change To
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.Parameters.AddWithValue("#STUDENT_NOL",studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
you are clear the parameters, but after that use #STUDENT_NO parameter. This parameter is not declare any where after clear ther parameters

UPDATE Command Parameters in C# For Access 2003 Not update

access 2003
vs 2010 c#
I cannot see where I have gone wrong. There is no error but no data is being updated. I have the insert, delete and edit working but I don't know why I can't get this to work. Please can someone kindly help me here, thanks in advance...
connection string
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:..\TempDB.mdb");
Update method...
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE [Family] SET [FirstName] = ?, [LastName] = ?, [FamilyDOB] = ?, [Medical] = ? WHERE [ID] = ?";
//tried this as well
//cmd.CommandText = "UPDATE [Family] SET [FirstName] = FirstName, [LastName] = #LastName, [DOB] = #StudentDOB, [Medical] = #Medical WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
Supply the parameter values in the same order as they appear in the SQL statement.
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
OleDB plus MS Access doesn't care about the parameter names, only their order.
The OLE DB.NET Framework Data Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.
Change this:
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
to:
cmd.Parameters.AddWithValue("?", txtFamID.Text);
cmd.Parameters.AddWithValue("?", txtFirstName.Text);
cmd.Parameters.AddWithValue("?", txtLastName.Text);
cmd.Parameters.AddWithValue("?", txtFamDOB.Text);
cmd.Parameters.AddWithValue("?", txtMedical.Text);
More: OleDbParameter Class

Oledb Update command

I make a program that saves and update a data from the database, I can save and read data, I can also update but the problem is, I can't select the "ID" as the index, here is my sample code using "ID" as the index,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();
}
and here is my update code that works, but the index is the "firstname",
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE FirstName = #firstname";
//cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();`
}
It works but the problem is I can't update the "FirstName", Is there a way that I can also update the Firstname? or use the "ID" as the index? thanks
I don't know what database you are going against, however, I don't know if the OleDB is being picky on the ordinal sequence of your parameters. ie: Have you tried putting your "ID" parameter in the last position to match the actual order of the fields of your update command? I don't know if it's throwing it out.
You should add the following code after the last line of ID:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Update Success!");
cn.Close();
}

Categories

Resources