Search code examples
c#ms-accessoledb

update data using oledb in c#


I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...

private void button2_Click(object sender, EventArgs e)
{
    connect.Open();
    string cid = textBox1.Text;
    string cfname = textBox2.Text;
    string clname = textBox3.Text;
    OleDbCommand command = new OleDbCommand();
    command.Connection = connect;
    command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
    if (connect.State == ConnectionState.Open)
    {
        try
        {
            command.ExecuteNonQuery();
            MessageBox.Show("DATA UPDATED");
            connect.Close();
        }
        catch (Exception expe)
        {
            MessageBox.Show(expe.Source);
            connect.Close();
        }
    }
    else
    {
        MessageBox.Show("ERROR");
    }
}

Solution

  • I believe your commandtext is where the trouble lies;

    command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
    

    You require a comma between the set statements, and also as Gino pointed out the speechmarks.

    Edit:

    It's better than you use parameters for your variables, your current method is open to SQL injection, eg.

        private void button2_Click(object sender, EventArgs e)
        {
            OleDbCommand command = new OleDbCommand(@"UPDATE Tcostumers
                                                        SET cfname = @CFName,
                                                            clname = @CLName
                                                        WHERE cid = @CID", connect);
    
            command.Parameters.AddWithValue("@CFName", textBox2.Text);
            command.Parameters.AddWithValue("@CLName", textBox3.Text);
            command.Parameters.AddWithValue("@CID", textBox1.Text);
    
            try
            {
                connect.Open();
            }
            catch (Exception expe)
            {
                MessageBox.Show(expe.Source);
            }
            try
            {
                command.ExecuteNonQuery();
    
                MessageBox.Show("DATA UPDATED");
            }
            catch (Exception expe)
            {
                MessageBox.Show(expe.Source);
            }
            finally
            {
                connect.Close();
            }
        }
    

    Its how I tend to format my code, so do as you will with it. Hope it helps.