[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 515
  • Last Modified:

c#2010 connect to access database

Hi

I am new to c# and gotta develop a Windows appplication.  Needs to connect with access database.

how is this done??

All tutts assume you are using sqlserverr


Cheers
0
cycledude
Asked:
cycledude
  • 3
  • 2
1 Solution
 
angus_young_acdcCommented:
To be honest it is basically the same code!  It is generally a case of replace 'Sql' with 'OleDb'

So
SqlConnection connection = new SqlConnection("My connection string");

Becomes

OleDbConnection connection = new OleDbConnection("my connection string");

Different namespaces but the syntax for them is generally the same.  The major difference would be in your connection string, but that isn't a big issue either.

For example: "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyDB.mdb"
0
 
angus_young_acdcCommented:
Example here, reading from a database with a table called MyTable and two columns one for UserName and one for UserBirthday and you want to read everything in this table.

                    OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyDb.mdb");
                    connection.Open();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM myTable");
                    cmd.CommandType = System.Data.CommandType.Text;
                    OleDbDataReader reader = default(OleDbDataReader);
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            // do something, eg
                            string myUser = reader["UserName"].ToString();
                            string myBirthday = reader["UserBirthday"].ToString();
                            // Do something else
                        }
                    }
                    connection.Close();

Open in new window

0
 
cycledudeAuthor Commented:
Thanks angus

I get a problem on the line

Reader = cmd.executereader ()


Invalidoperationexception

Executereader connection property has not been initialised

Any ideas?
0
 
angus_young_acdcCommented:
Whoops missed a line!

Just after this: cmd.CommandType = System.Data.CommandType.Text;


put this:
cmd.Connection = connection;
0
 
cycledudeAuthor Commented:
dude, you are a star!
thanks
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now