Connect to Microsoft Access .mdb database using C#
Here is a simple example that will tell you how to connect to microsoft access (mdb) files in C# .NET. To do this you have to make use OLEDB connector
The first you need is to use OLEDB connector.
First we need to use oledb connector namespace.
using System.Data.OleDb;
Now we need to create an instance of OleDbConnection object. The following will be the connection string required to use as parameter of OleDbConnection instance object
private string conStr = @"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=contact.mdb;Jet OLEDB:Database Password=123456";
Here contact.mdb is the microsoft access database file located at the same directory to the exe file.
Now we can look at the whole code at once.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
public class Program
{
private static OleDbConnection con;
static void Main()
{
try
{
con = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=contact.mdb;Jet OLEDB:Database Password=123456"); // connection string change database name and password here.
con.Open(); //connection must be openned
OleDbCommand cmd = new OleDbCommand("SELECT * from contact", con); // creating query command
OleDbDataReader reader = cmd.ExecuteReader(); // executes query
while(reader.Read()) // if can read row from database
{
Console.WriteLine(reader.GetValue(1).ToString() + " = " + reader.GetValue(3).ToString()); // Get column 1 and column 3 value and print
}
}
catch(Exception ex)
{
Console.WriteLine("Ex: "+ex); // shows exception message in console if any errors occured
}
finally
{
con.Close(); // finally closes connection
}
}
}
}
Hi,
I am connecting to access db that is on remote server. But somehow I can’t. I am getting this error : Internet client error. Cannot Connect to Server.
Where am I going wrong?
Can you help me in this?
Regards
Prashant
1) make sure you can access the remove server
2) make sure you are trying to connect to the remote server with the same protocol, C# do with local file
3) make sure the port you are using is remotely accessible
Nice article sir