Gathering data from Access database

可紊 提交于 2019-12-01 01:53:05

From here, you use the OleDbDataReader:

using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;

class MainClass
{
  static void Main(string[] args)
  {
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\Northwind.mdb";

    OleDbConnection conn = new OleDbConnection(connectionString);

    string sql = "SELECT * FROM Orders";

    OleDbCommand cmd = new OleDbCommand(sql, conn);

    conn.Open();

    OleDbDataReader reader;
    reader = cmd.ExecuteReader();

    while (reader.Read()) 
    {
      Console.Write(reader.GetString(0).ToString() + " ," );
      Console.Write(reader.GetString(1).ToString() + " ," );
      Console.WriteLine("");
    }

    reader.Close();
    conn.Close();
  }
}

If you can fill a DataSet, you have all data (fields) in memory.

  • In your Project, use the Data menu to add a DataSource.
  • Follow the Wizard. It will create a Typed DataSet for you.
  • Drag the new DataSource to a Form. That will show you the code to fill the DS.

I wrote this test program to retrieve data from a DAO database. This should work for you too.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;


namespace TestReadCfg
{
  class Program
  {
    static void Main(string[] args)
    {
        string connectionString =
            "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
        + "c:\\Avtron\\addapt\\Configuration\\testDao.db;Jet OLEDB:Database Password=RainbowTrout;";

        string queryString = "SELECT * from Sections order by Address";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            OleDbCommand command = new OleDbCommand(queryString, connection);
            try
            {
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
                int iRecNbr = 1;
                while (reader.Read())
                {
                    String sRecord = string.Empty;
                    sRecord = string.Format("Record {0}: ", iRecNbr);
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        sRecord += string.Format("{0} ", reader[i].ToString());
                    }
                    Console.WriteLine(sRecord);
                    iRecNbr++;
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();

        }

   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!