Search code examples
c#asp.netoledbms-access-2010

I can't add data from .NET to Access 2010


Button.Click event :

OleDbConnection db_conn;
    db_conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\veri.accdb;Persist Security Info=False");
    try
    {
        db_conn.Open();
        OleDbCommand db_command = new OleDbCommand("Insert INTO data(Name,Mail) Values( '" + TextBox1.Text + "','" + TextBox2.Text + "')", db_conn);
        db_command.ExecuteNonQuery();
        db_conn.Close();
        Label5.Text = "Succesfully!";
    }catch{
        Response.Write("There is something wrong!");
    }
  • The Result is : CATCH : There is something wrong!

  • My IDE is Visual Studio 2012

  • My Access version is 2010

  • My database name is veri.accdb


Solution

  • Try to change the connection string to

    db_conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;
                                    Data Source=C:\veri.accdb;Persist Security Info=False");
    

    The simple @ in front of the string is required when you have a special character like the backslash. (or use two backslashes like C:\\veri.accdb)

    Said that you have another problem. The root of the C: drive is not a good place to position your database because it requires special permissions and usually is a readonly.

    Finally the string concatenation is a very bad practice and should be changed to a parameterized query

    string cmdText = "Insert INTO data(Name,Mail) Values(?,?)";
    using(OleDbConnection db_conn = new OleDbConnection(@"......."))
    using(OleDbCommand db_command = new OleDbCommand(cmdText, db_conn)) 
    {
        try
        {
            db_conn.Open();
            db_command.Parameters.AddWithValue("@p1",TextBox1.Text);
            db_command.Parameters.AddWithValue("@p2",TextBox2.Text);
            db_command.ExecuteNonQuery();
            Label5.Text = "Succesfully!";
        }
        catch(Exception ex)
        {
            // It is preferable to not catch the exception if you don't do anything, 
            // but if you catch then, at least, report what is wrong
            Response.Write("There is something wrong!" + ex.Message);
        }
     }