Connecting Visual Studio with an Access database

1

I have a connection string with the Access database:

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\lentes.accdb;Persist Security Info=False";

When I run this code I always give the error "The keyword 'Provider' is not supported."

PS. has nothing after that code yet, that's all:

 string strcon = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\lentes.accdb;Persist Security Info=False";
            SqlConnection con = new SqlConnection(strcon);
            con.Open();

Then I execute the try and catch to see the error and the error that I said.

    
asked by anonymous 09.07.2018 / 05:15

1 answer

3

You are trying to create a connection to ACCESS using the System.Data.SqlClient assembly.

For Access, you will have to use the System.Data.OleDbClient assembly

Here is an example code:

public void ConnectToAccess()
{


  System.Data.OleDb.OleDbConnection conn = new 
      System.Data.OleDb.OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}
    
09.07.2018 / 16:50