Search code examples
c#sqlwinformsms-accessoledb

C# Windows Form App With Ms Access Failed to Insert Data


i know this topic is already discuss many time, but i still dont get my problem solved..

ok, i have a form to insert registration data into MS Access Database (2007), but my code doesnt insert data into database, and there are no errors, here is the code:

OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter(); 


 private void btnSave_Click(object sender, EventArgs e)
        {

string idCard = this.txtID.Text;
string name = this.txtName.Text;
DateTime dateBirth = this.dateEdit1.DateTime;

cn.Open();
cmd.CommandText = "Insert into tb_reg (id, name, dateBirth, blood_type) Values(@id,@name,@dateBirth)";

                    cmd.Parameters.AddWithValue("@id", idCard);
                    cmd.Parameters.AddWithValue("@name", name);                    
                    cmd.Parameters.AddWithValue("@dateBirth", dateBirth.ToString());

adapter.InsertCommand = cmd;
                    int result = cmd.ExecuteNonQuery();

                    if (result > 0)
                        MessageBox.Show("Succesfully added");
                    else
                        MessageBox.Show("try again");
                    cn.Close();
         }

the message box always show "successfully added".


Solution

  • I had something like this in a project of mine. Maybe it works for you:

    string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type); 
    OleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));
    cmd.Connection.Open();
    
    int numberAdded = cmd.ExecuteNonQuery();
    
    if (numberAdded < 1)
    {
         //do something, the data was not added
    }
    else
    {
         //be happy :)
    }
    cmd.Connection.Close();  
    

    As I said, that worked for me.