C# 减少对数据库的多次调用
我有一个代码库,它遍历记录列表并执行以下操作C# 减少对数据库的多次调用,c#,database,vb.net,C#,Database,Vb.net,我有一个代码库,它遍历记录列表并执行以下操作 'select * from Table to see if fields exist then later in the interation 'select * from Table to retreive some data then farther down in the interation select field1, field2 from Table to get certain pieces of information 我需
'select * from Table to see if fields exist
then later in the interation
'select * from Table to retreive some data
then farther down in the interation
select field1, field2 from Table to get certain pieces of information
我需要为每个记录执行所有这些功能。如果我为每个记录调用一次查询,并将数据保存在datatable中,然后从中检索我需要的数据,过程会加快吗?或者,有没有另一种更有效的方法不必对同一个表进行3db调用,从而加快处理速度?您可以将查询数据缓存到。为了简化工作,我编写了CMyDynaset类,它用数据库中的数据填充DataTable。下面是如何将其用于MySQL的示例:
using System;
using System.Data.Common;
using MySql.Data.MySqlClient;
namesapce MyProg
{
class Program
{
private const string strMyConnection = "Host=localhost;Database=mydb;User Id=myuser;Password=mypsw";
static void Main(string[] args)
{
using (MySqlConnection myConnection = new MySqlConnection(strMyConnection))
{
using (MyDb.CMyDynaset dyn = new MyDb.CMyDynaset(myConnection, MySqlClientFactory.Instance))
{
// populate dyn.Table (System.Data.DataTable)
dyn.Init("select * from Table");
dyn.Load();
// access fields
foreach (DataColumn column in dyn.Table.Columns)
{
// ...
}
// get data
long nCountAll = dyn.Table.Rows.Count; // rows count
foreach (DataRow row in dyn.Table.Rows)
{
Object val1 = row[1]; // acess by index
Object val2 = row["id"]; // acess by name
// ...
}
// update data
dyn.Table.Rows[0]["name"] = "ABC";
dyn.Update();
}
}
}
}
}
CMyDynaset类(CMyDynaset.cs):
//CMyDynaset.cs
使用制度;
使用System.Data.Common;
名称空间MyDb
{
///
///CMyDynaset的摘要说明。
///
公共类CMyDynaset:IDisposable
{
public System.Data.DataTable Table=null;
//私人的
私有数据库连接myConnection=null;
私有DbProviderFactory myFactory=null;
私有DbDataAdapter dataAdap=null;
私有DbCommandBuilder cmdBld=null;
私有布尔模式=false;
公共CMyDynaset(DbConnection,DBPROVIDER工厂)
{
this.myConnection=conn;
this.myFactory=工厂;
}
#区域IDisposable成员
公共空间处置()
{
如果(this.Table!=null)
{
this.Table.Dispose();
表=null;
}
如果(this.cmdBld!=null)
{
this.cmdBld.Dispose();
this.cmdBld=null;
}
如果(this.dataAdap!=null)
{
this.dataAdap.Dispose();
this.dataAdap=null;
}
//此对象将通过Dispose方法清除。
//因此,您应该调用GC.superssfalize来
//将此对象从终结队列中移除
//并阻止此对象的终结代码
//从第二次执行开始。
总干事(本);
}
#端区
//初始化
公共void Init(字符串strSelect)
{
DbCommand cmdSel=this.myConnection.CreateCommand();
cmdSel.CommandText=strSelect;
this.dataAdap=this.myFactory.CreateDataAdapter();
this.dataAdap.SelectCommand=cmdSel;
this.cmdBld=this.myFactory.CreateCommandBuilder();
this.cmdBld.DataAdapter=this.dataAdap;
this.Table=new System.Data.DataTable();
//模式
this.bIsSchema=false;
}
public void AddParameter(字符串名称、对象值)
{
DbParameter param=this.dataAdap.SelectCommand.CreateParameter();
param.ParameterName=名称;
参数值=值;
this.dataAdap.SelectCommand.Parameters.Add(param);
}
公共void AddParameter(DbParameter param)
{
this.dataAdap.SelectCommand.Parameters.Add(param);
}
//开,关
私人作废打开(参考bool bClose)
{
if(this.myConnection.State==System.Data.ConnectionState.Closed)
{
this.myConnection.Open();
bClose=true;
}
如果(!this.bIsSchema)
{//schema
this.dataAdap.FillSchema(this.Table,System.Data.SchemaType.Mapped);
this.bIsSchema=true;
}
}
私人作废关闭(bool bClose)
{
如果(bClose)
this.myConnection.Close();
}
//加载、更新
公共空荷载()
{
bool bClose=false;
尝试
{
此.Table.Clear();
此。打开(参考bClose);
this.dataAdap.Fill(this.Table);
}
catch(System.Exception-ex)
{
掷骰子;
}
最后
{
这个。关闭(bClose);
}
}
公共无效更新()
{
bool bClose=false;
尝试
{
此。打开(参考bClose);
this.dataAdap.Update(this.Table);
}
catch(System.Exception-ex)
{
掷骰子;
}
最后
{
这个。关闭(bClose);
}
}
}
}
为什么不在开始时选择整个迭代过程中需要的所有字段,然后处理不存在的情况?
// CMyDynaset.cs
using System;
using System.Data.Common;
namespace MyDb
{
/// <summary>
/// Summary description for CMyDynaset.
/// </summary>
public class CMyDynaset : IDisposable
{
public System.Data.DataTable Table = null;
// private
private DbConnection myConnection = null;
private DbProviderFactory myFactory = null;
private DbDataAdapter dataAdap = null;
private DbCommandBuilder cmdBld = null;
private bool bIsSchema = false;
public CMyDynaset(DbConnection conn, DbProviderFactory factory)
{
this.myConnection = conn;
this.myFactory = factory;
}
#region IDisposable Members
public void Dispose()
{
if (this.Table != null)
{
this.Table.Dispose();
this.Table = null;
}
if (this.cmdBld != null)
{
this.cmdBld.Dispose();
this.cmdBld = null;
}
if (this.dataAdap != null)
{
this.dataAdap.Dispose();
this.dataAdap = null;
}
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
// Init
public void Init(string strSelect)
{
DbCommand cmdSel = this.myConnection.CreateCommand();
cmdSel.CommandText = strSelect;
this.dataAdap = this.myFactory.CreateDataAdapter();
this.dataAdap.SelectCommand = cmdSel;
this.cmdBld = this.myFactory.CreateCommandBuilder();
this.cmdBld.DataAdapter = this.dataAdap;
this.Table = new System.Data.DataTable();
// schema
this.bIsSchema = false;
}
public void AddParameter(string name, object value)
{
DbParameter param = this.dataAdap.SelectCommand.CreateParameter();
param.ParameterName = name;
param.Value = value;
this.dataAdap.SelectCommand.Parameters.Add(param);
}
public void AddParameter(DbParameter param)
{
this.dataAdap.SelectCommand.Parameters.Add(param);
}
// Open, Close
private void Open(ref bool bClose)
{
if (this.myConnection.State == System.Data.ConnectionState.Closed)
{
this.myConnection.Open();
bClose = true;
}
if (!this.bIsSchema)
{ // schema
this.dataAdap.FillSchema(this.Table, System.Data.SchemaType.Mapped);
this.bIsSchema = true;
}
}
private void Close(bool bClose)
{
if (bClose)
this.myConnection.Close();
}
// Load, Update
public void Load()
{
bool bClose = false;
try
{
this.Table.Clear();
this.Open(ref bClose);
this.dataAdap.Fill(this.Table);
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
this.Close(bClose);
}
}
public void Update()
{
bool bClose = false;
try
{
this.Open(ref bClose);
this.dataAdap.Update(this.Table);
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
this.Close(bClose);
}
}
}
}