我想从Access数据库的某些表中收集一些数据,我在网上找到了一些解决方案,但我还没有找到填充数据表或数据集的方法,并且无法正确获取每个字段。
我是否更容易获得整个表格然后只获得我想要的信息,或者我应该在访问数据库中进行大量搜索以获得我想要的每次?任何代码片段?
信息:
- [编辑] -
子问题:
Connecting to ACCDB format MS-ACCESS database through OLEDB
答案 0 :(得分:3)
从here开始,您使用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();
}
}
答案 1 :(得分:1)
如果可以填充DataSet,则内存中包含所有数据(字段)。
答案 2 :(得分:0)
我编写了这个测试程序来从DAO数据库中检索数据。这对你也有用。
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();
}
}
}