Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been creating a software in C#. I tried to update some information in my Access database. Here's my database fields.Date ,total_h, W_hours, delay_h. Date is the Primary key. So I want to Update data where Date="datetimePicker.text". here is the Code What I tried.

C#
try
{
    connection.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = connection;               
    string update = "update summery_data set total_h='"+tHour+"', delay_h='"+delay+"' WHERE Date= " + dateTimePicker1.Text + " ";      
                    cmd.CommandText = update;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show(" Updated successfully");
                    connection.Close();
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}


The Program is running properly without any Exception and displaying the "Updated successfully" message also. But when I open and Check the database the data has not been updated. I can't Understand what the problem is...?. please help me someone knows about it.

What I have tried:

The Program is running properly without any Exception and displaying the "Updated successfully" message also. But when I open and Check the database the data has not been updated.
Posted
Updated 26-Jun-16 2:41am
Comments
[no name] 26-Jun-16 8:23am    
Check the return value of OleDbCommand. It returns the "number of affected rows". Most probably it is Zero because most probably your WHERE clause does not match.

1 solution

Don't do it like that. Do not 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. Use Parametrized queries instead.
The chances are that this will cure your problem at the same time: it's very likely that the WHERE clause is not matching any records.
C#
string update = "update summery_data set total_h=@TH, delay_h=@DH WHERE Date=@DAT";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("@TH", tHour);
cmd.Parameters.AddWithValue("@DH", delay);
cmd.Parameters.AddWithValue("@DAT",dateTimePicker1.Value);
 
Share this answer
 
Comments
Maciej Los 26-Jun-16 15:00pm    
5ed!

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900