Using Access databases in C#?
ado.net, c#, ms-access
Solution
See this walkthrough for using ADO.NET to edit an Access database.
Now while that example is using a web application, don't worry, the classes being used are still applicable for a console application as well.
The main classes you will need to use are:
- OleDbConnection
- OleDbCommand
- OleDbDataReader
The documentation of the classes above all have code samples that are console app examples.
Below is a code snippet for use in a console app (remember to add the: `using System.Data.OleDb;`
string connectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:\path\to\your\database.mdb;" +
@"User Id=;Password=;";
string queryString = "SELECT Foo FROM Bar";
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(queryString, connection))
{
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Also, just noticed you explicitly said an .accdb database. For this grab the Microsoft Access Database Engine 2010 Redistributable. The provider in the connection string would then need to be changed to: `Microsoft.ACE.OLEDB.12.0` (see notes at that link for more info).
Problem
How would I use a Microsoft Access (`.accdb`) database in C# (console application, not web asp.net)? From what I've read, I'll need to use `ADO.NET`, but I'm really at a loss as to how to do this in a C# console application. In PHP with `MySQL`, I'd be looking for `mysqli_construct` Could anyone point me towards a tutorial or documentation that would help me with that? I'm trying to use it as a way to store and access data for my non-web, non ASP.NET application, if that changes anything. Thanks!