将DataSet一次性保存到数据库中去的方法
将DataSet一次性保存到数据库中去的方法
try
{
SqlConnection Conn=this.CreateConnection();
try
{
//得到原始数据
SqlCommand cmd=new SqlCommand(Sql,Conn);
cmd.CommandTimeout=COMMANDTIMEOUT;
cmd.CommandType=CommandType.Text;
SqlDataAdapter da=new SqlDataAdapter(cmd);
SqlCommandBuilder cb=new SqlCommandBuilder(da);
DataSet dsNew=new DataSet();
da.Fill(dsNew,TableName);
foreach(DataRow drOld in Data.Tables[0].Rows)
{
if(drOld.RowState==DataRowState.Added)//增加记录
{
DataRow drNew=dsNew.Tables[0].NewRow();
foreach(DataColumn dcNew in dsNew.Tables[0].Columns)
{
if(!dcNew.ReadOnly)
{
string strField=dcNew.ColumnName;
drNew[strField]=drOld[strField];
}
}
dsNew.Tables[0].Rows.Add(drNew);
}
else if(drOld.RowState==DataRowState.Modified)//修改记录
{
string strKey=drOld[KeyFieldName,DataRowVersion.Original].ToString();
DataRow[] drs=dsNew.Tables[0].Select(KeyFieldName+"='"+strKey+"'");
if(drs.GetLength(0)>0)
{
DataRow drModify=drs[0];
foreach(DataColumn dcNew in dsNew.Tables[0].Columns)
{
if(!dcNew.ReadOnly)
{
string strField=dcNew.ColumnName;
drModify[strField]=drOld[strField];
}
}
}
}
else if(drOld.RowState==DataRowState.Deleted)//删除记录
{
string strKey=drOld[KeyFieldName,DataRowVersion.Original].ToString();
DataRow[] drs=dsNew.Tables[0].Select(KeyFieldName+"='"+strKey+"'");
if(drs.GetLength(0)>0)
{
for(int i=drs.GetLength(0)-1;i>=0;i--)
{
DataRow drDelete=drs[i];
drDelete.Delete();
}
}
}
}
da.Update(dsNew,TableName);
}
catch(Exception e)
{
throw(e);
}
finally
{
this.Dispose(Conn);
}
}
catch(Exception e)
{
throw(e);
}