我使用OleDbDataAdapter类从Access(.mdb)文件中获取数据。
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Environment.CurrentDirectory+"\Data.mdb;Jet OLEDB:Database Password=pass");
OleDbCommand com = new OleDbCommand(query, con);
DataTable dt = new DataTable();
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(com);
oda.Fill(dt);
oda.Dispose();
com.Parameters.Clear();
con.Close();
return dt;
问题是,通过调试我发现,oda.Fill(dt)
需要很长时间才能执行。(约10秒)
我在数据库中有50000条记录,我只需要检索1行。
请帮忙。提前谢谢。
如果您只需要一行,请尝试使用如下所示的数据读取器,您将需要调整数据库名称、字段列表等部分。
注意,我将输出写入IDE输出窗口,因此在尝试使用代码/数据时将其打开。
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
int id = 0;
if (int.TryParse(textBox1.Text, out id))
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.DataSource = Path.Combine(Application.StartupPath, "Database1.mdb");
using (OleDbConnection cn = new OleDbConnection(Builder.ConnectionString))
{
string selectStatement = "SELECT UserName, JoinMonth FROM Users WHERE Identifier = @Identifier";
using (OleDbCommand cmd = new OleDbCommand { CommandText = selectStatement, Connection = cn })
{
cmd.Parameters.Add(new OleDbParameter { ParameterName = "@Identifier", DbType = DbType.Int32, Value = id });
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
Console.WriteLine("{0} - {1}", dr.GetString(0), dr.GetString(1));
}
else
{
Console.WriteLine("Not located");
}
}
}
}
}
}