Use OleDb classes to read data from an Access database
OleDb classes allow you to manipulate data stored in an Access database. In this simple example we see how do I use.
Code:
// Define the connection string
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
Server.MapPath("~/App_Data/Northwind.mdb");
// Define the SELECT command
string selectCommand = "SELECT Employees.LastName AS Surname, Employees.FirstName AS Name, Employees.City " +
"FROM Employees " +
"ORDER BY Employees.LastName";
try
{
// Create a Connection
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Create a DataReader
OleDbDataReader dataReader = null;
// Create a Command
OleDbCommand command = new OleDbCommand(selectCommand, connection);
connection.Open();
dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (dataReader.Read())
{
string record = dataReader.GetValue(0).ToString() + " " +
dataReader.GetValue(1).ToString() + " (" +
dataReader.GetValue(2).ToString() + ") ";
Response.Write(record + "<br />");
}
dataReader.Close();
connection.Close();
}
}
catch (OleDbException excp)
{
if(debug)
Response.Write("Error:<br />" + excp.ToString() );
}
The example produces the following result:
Buchanan Steven (London)
Callahan Laura (Seattle)
Davolio Nancy (Seattle)
Dodsworth Anne (London)
Fuller Andrew (Tacoma)
King Robert (London)
Leverling Janet (Kirkland)
Peacock Margaret (Redmond)
Suyama Michael (London)