Connection to a MS Access database

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How to get connection to a MS Access database?
How to read from a MS Access database?
How to close the connection to a MS Access database?
 
Hi

Accessing an Access database is just as easy as accessing any other
database. You should use OleDb data providers to establish a connection. A
connection string is something like this. The Provider is the most important
thing to remember. Note, that the database must exist.

dbconn.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\inetpub\wwwroot\studydotnet\study.mdb";

You can read data just as easily as with any other datasource. You can use a
DataAdapter to fill a DataSet, or use the DataReader to read data. In either
case, you can use SQL SELECT statement to get the data.

And closing, well, simply call Close() on the connection. It really doesn't
work that much different from other data providers.

-Artur
 
Hi,

Here's the code

string strConnect
= "Provider=Microsoft.Jet.OLEDB.4.0 ;Data
Source="+Server.MapPath(".\\db\\forum.mdb");
string strSelect = "SELECT * FROM
topics ORDER BY TopicCreateDate DESC";
try
{

//create a new
OleDbConnection object using the connection string
OleDbConnection objConnect
= new OleDbConnection(strConnect);

//open the connection to
the database
objConnect.Open();

//create a new
OleDbCommand using the connection object and select
statement
OleDbCommand objCommand =
new OleDbCommand(strSelect, objConnect);

//declare a variable to
hold a DataReader object
OleDbDataReader
objDataReader;

//execute the SQL
statement against the command to fill the DataReader
objDataReader =
objCommand.ExecuteReader();

DataGrid1.DataSource =
objDataReader;
DataGrid1.DataBind();

if (DataGrid1.Items.Count
== 0)
{
outError.InnerHtml
= "There are currently no Postings for this topic, start
the posts with the form above.";
}

//close the DataReader and
Connection
objDataReader.Close();
objConnect.Close();

}

catch (Exception objError)
{

//display error details
outError.InnerHtml = "<b>*
Error while accessing data</b>.<br />"
+ objError.Message
+ "<br />" + objError.Source;
return; //and stop
execution
}

Irfan
 
Sorry, seems to be self explainatory!. it shows the usage
of a datagrid control and how the data from db is attached
to it.
 
Back
Top