How to connect to a MS Access file (mdb) using C#?

前端 未结 6 795
迷失自我
迷失自我 2020-11-27 21:24

I\'m trying to connect to a mdb file and I understand that I would need Microsoft.OLEDB.JET.4.0 data provider. Unfortunately, I do not have it installed on the

6条回答
  •  抹茶落季
    2020-11-27 21:28

    Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

    using System.Data;
    using System.Data.OleDb;
    
    string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                               "Data Source=C:\myPath\myFile.mdb;" +                                    
                               "Persist Security Info=True;" +
                               "Jet OLEDB:Database Password=myPassword;";
    try
    {
        // Open OleDb Connection
        OleDbConnection myConnection = new OleDbConnection();
        myConnection.ConnectionString = myConnectionString;
        myConnection.Open();
    
        // Execute Queries
        OleDbCommand cmd = myConnection.CreateCommand();
        cmd.CommandText = "SELECT * FROM `myTable`";
        OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
    
        // Load the result into a DataTable
        DataTable myDataTable = new DataTable();
        myDataTable.Load(reader);
    }
    catch (Exception ex)
    {
        Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
    }
    

提交回复
热议问题