首先读取Excel中数据,存储在一个DataSet中,然后用这个DataSet更新数据库中对应的表(该表的主键为自动编号,Excel中没有该列)。
我用SqlDataAdaptor的Update方法更新,用SqlCommandBuilder自动获取相应命令。但老是弹出“动态Selectcommand不能自动生成DeleteCommand”的提示。
后来,我在DataSet中增加了主键,还是这样提示。。
请高手指教。
谢谢。
我用SqlDataAdaptor的Update方法更新,用SqlCommandBuilder自动获取相应命令。但老是弹出“动态Selectcommand不能自动生成DeleteCommand”的提示。
后来,我在DataSet中增加了主键,还是这样提示。。
请高手指教。
谢谢。
{
if(dsSource == null) throw new ArgumentNullException("dsSource");
if(srcTable == null || srcTable =="") srcTable = dsSource.Tables[0].TableName;
if(selectCommand == null || selectCommand.CommandText == "") throw new ArgumentNullException("initSelect");
DataSet dsSql = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(); try
{
sda.SelectCommand = selectCommand;
sda.Fill(dsSql,srcTable);
sda.MissingSchemaAction = MissingSchemaAction.AddWithKey; if(dsSql.Tables[0].Columns.Count!=dsSource.Tables[0].Columns.Count)
{
throw new ArgumentException("查询语句中的列数与作为导入数据源的dsSource中的列数不一致。");
}
if(primaryKey.Length>0)
{
System.Data.DataColumn[] pKs = new System.Data.DataColumn[primaryKey.Length];
for(int i=0; i < primaryKey.Length; i++)
pKs[i] = dsSql.Tables[0].Columns[primaryKey[i]];
dsSql.Tables[0].PrimaryKey = pKs;
}
sda.FillSchema(dsSql,SchemaType.Source,srcTable); dsSql.Merge(dsSource,true,MissingSchemaAction.AddWithKey); SqlCommandBuilder cmdbd = new SqlCommandBuilder(sda);
sda.InsertCommand = cmdbd.GetInsertCommand();
if(primaryKey.Length>0)
{
sda.DeleteCommand = cmdbd.GetDeleteCommand();
sda.UpdateCommand = cmdbd.GetUpdateCommand();
} int result = sda.Update(dsSql,srcTable);//更新数据库 dsSql.AcceptChanges();
}
catch (Exception ex)
{
throw ex;
}
finally
{
dsSql.Dispose();
dsSource.Dispose();
sda.Dispose();
GC.Collect();
}
}
http://blog.csdn.net/zhzuo/archive/2004/08/06/67016.aspx
http://blog.csdn.net/zhzuo/archive/2004/08/06/67037.aspx
------------------------------------------------
根据你的表自己写对应的Update和Delete语句就得啦!