Home > Blockchain >  How do I connect an MS Access DB to a C# program in Visual Studio?
How do I connect an MS Access DB to a C# program in Visual Studio?

Time:05-30

I have written a simple program in C# using WinForms .NET Core and I am having trouble linking the database. All the online tutorials provide C# code that uses OLE DB connectivity however it seems that it only works for .NET Framework and not .NET Core. Can anyone provide the C# code of Odbc? I have added the MS database in Data Connections and now I just need the C# code for my submit button and any connection strings. I also have an SQLite Database I could add as opposed to MS Access.

CodePudding user response:

I would opt for SQLite Database but if you want MS-Access the following provides how to connect where the key is installing the package below.

Try the following coded with .NET Core, C#9.

Add System.Data.OleDb (I dropped down several versions, from 7 to 6) from NuGet. Add a class to your project and change the connection string for your database, here it's in the app folder.

public class Operations
{
    public static string ConnectionString =>
        "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=NorthWind.accdb";


    public static (bool succcess, Exception exception) TestConnection()
    {
        using var cn = new OleDbConnection { ConnectionString = ConnectionString };
        try
        {
            cn.Open();
            return (true, null);
        }
        catch (Exception e)
        {
            return (false, e);
        }
    }
}

Run the above code

var (success, exception) = Operations.TestConnection();
if (success)
{
    MessageBox.Show("Good to go");
}
else
{
    MessageBox.Show(exception.Message);
}
  • Related