John.Smith
John.Smith

Reputation: 87

Confused about setting up a connection to a microsoft access database while using C#

Ok, so I've been looking everywhere on how to connect a microsoft access database to a C# command line application. I have experience in visual studio when I was doing visual basic so I connected the database to the project via the "add new data source" menu. Now I'm here I have no clue how to declare the connection and open it. I know the basics of SQL code so that's not really a problem right now, it's just the connecting part. Looking around, I've found this:

using System.Data.SqlClient;
string connectionString = null;

connectionString = ;
SqlConnection cnn ;
cnn = new SqlConnection(connectionString);
try
{
    cnn.Open();
    Console.WriteLine("Connection Open!");
    cnn.Close();
}
catch (Exception ex)
{
    Console.WriteLine("Error: Connection Cannot be Opened!");
}

But I have no clue what this does. If this is wrong can someone please correct me and explain it. Please keep it as simple as possible.

Upvotes: 0

Views: 75

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

Setting the connectionString = null won't work!

See: http://www.connectionstrings.com/ for help on connection strings. This is really a great site.

And if you want a connection to Access, you need an OleDbConnection, not a SqlConnection. The latter is used for connections to SQL-Server.

You can find an example here: Getting values back from OleDbDataReader reading from Access database.

Upvotes: 1

Cetin Basoz
Cetin Basoz

Reputation: 23797

You simply use OleDb* instead of Sql*. ie:

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\MyFolder\Northwind.accdb";
using( OleDbConnection cnn = new OleDbConnection(connectionString))
{
    try
    {
        cnn.Open();
        Console.WriteLine("Connection Open!");
        cnn.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: Connection Cannot be Opened!");
    }
}

PS: I wouldn't recommend you using access as if it is a database. It is not a database. It is the wolf disguised like a sheep. If you don't care about your data then OK.

Upvotes: 3

Related Questions