主题:[转帖]ADO.NET实现批量SQL更新
1. 反射数据适配器对象.
Type m_AdapterType = typeof(SqlDataAdapter);
IDbDataAdapter m_Adapter = (IDbDataAdapter)Activator.CreateInstance(m_AdapterType);
MethodInfo m_AddToBatch = m_AdapterType.GetMethod("AddToBatch", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_ClearBatch = m_AdapterType.GetMethod("ClearBatch", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_InitializeBatching = m_AdapterType.GetMethod("InitializeBatching", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_ExecuteBatch = m_AdapterType.GetMethod("ExecuteBatch", BindingFlags.NonPublic | BindingFlags.Instance);
2.初始化适配器
IDbCommand cmd = Connection.CreateCommand();
//事务
cmd.Transaction = Transaction;
switch (bcmd)//命令的类型, 枚举
{
case BatchCommandType.Insert:
m_Adapter.InsertCommand = cmd;
break;
case BatchCommandType.Update:
m_Adapter.UpdateCommand = cmd;
break;
case BatchCommandType.Delete:
m_Adapter.DeleteCommand = cmd;
break;
}
m_InitializeBatching.Invoke(m_Adapter, null);
3.将命令遍历, 添加到适配器中.
foreach (object parameter in parameterObjects)
{
//创建命令
IDbCommand mycmd = ........................
//添加到批命令
m_AddToBatch.Invoke(m_Adapter, new object[1] { mycmd });
}
4. 执行命令
OpenConnection();
//执行批处理
rows = (int)m_ExecuteBatch.Invoke(m_Adapter, null);
5.关闭
m_ClearBatch.Invoke(m_Adapter, null);
IDisposable dis = m_Adapter as IDisposable;
if (dis != null)
dis.Dispose();
m_Adapter = null;
转载请注明来自: http://www.caodong.net/Article/830.html
Type m_AdapterType = typeof(SqlDataAdapter);
IDbDataAdapter m_Adapter = (IDbDataAdapter)Activator.CreateInstance(m_AdapterType);
MethodInfo m_AddToBatch = m_AdapterType.GetMethod("AddToBatch", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_ClearBatch = m_AdapterType.GetMethod("ClearBatch", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_InitializeBatching = m_AdapterType.GetMethod("InitializeBatching", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo m_ExecuteBatch = m_AdapterType.GetMethod("ExecuteBatch", BindingFlags.NonPublic | BindingFlags.Instance);
2.初始化适配器
IDbCommand cmd = Connection.CreateCommand();
//事务
cmd.Transaction = Transaction;
switch (bcmd)//命令的类型, 枚举
{
case BatchCommandType.Insert:
m_Adapter.InsertCommand = cmd;
break;
case BatchCommandType.Update:
m_Adapter.UpdateCommand = cmd;
break;
case BatchCommandType.Delete:
m_Adapter.DeleteCommand = cmd;
break;
}
m_InitializeBatching.Invoke(m_Adapter, null);
3.将命令遍历, 添加到适配器中.
foreach (object parameter in parameterObjects)
{
//创建命令
IDbCommand mycmd = ........................
//添加到批命令
m_AddToBatch.Invoke(m_Adapter, new object[1] { mycmd });
}
4. 执行命令
OpenConnection();
//执行批处理
rows = (int)m_ExecuteBatch.Invoke(m_Adapter, null);
5.关闭
m_ClearBatch.Invoke(m_Adapter, null);
IDisposable dis = m_Adapter as IDisposable;
if (dis != null)
dis.Dispose();
m_Adapter = null;
转载请注明来自: http://www.caodong.net/Article/830.html