首先读取Excel中数据,存储在一个DataSet中,然后用这个DataSet更新数据库中对应的表(该表的主键为自动编号,Excel中没有该列)。
我用SqlDataAdaptor的Update方法更新,用SqlCommandBuilder自动获取相应命令。但老是弹出“动态Selectcommand不能自动生成DeleteCommand”的提示。
后来,我在DataSet中增加了主键,还是这样提示。。
请高手指教。
谢谢。

解决方案 »

  1.   

    public static void UpdateDataset(DataSet dsSource,string srcTable,SqlCommand selectCommand,string[] primaryKey)
    {
    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();
    }
    }
      

  2.   

    如果表没有主键的话是不能用SqlCommandBuilder对象自动生成SQL语句的,需要手动指定UpdateCommand、DeleteCommand等对象要执行的SQL语句才可以。
      

  3.   

    补充一句,在DataSet里指定主键是没用的,SqlDataAdapter对象在填充DataSet时SelectCommand就已经确定了,自动生成SQL语句就是根据SelectCommand中的SQL语句生成的,如果没主键就无法确定更新的行索引。
      

  4.   

    多谢各位提醒,但能不能更改SelectCommand的主键呢?
      

  5.   

    强烈建议不要使用SqlCommandBuilder来生成Sql,这样出了问题很难找问题,没有主键就自己写吧,可以参考一下这里,
    http://blog.csdn.net/zhzuo/archive/2004/08/06/67016.aspx
    http://blog.csdn.net/zhzuo/archive/2004/08/06/67037.aspx
      

  6.   

    有没有谁写过UpdateCommand、DeleteCommand的??
      

  7.   

    有没有谁写过UpdateCommand、DeleteCommand的??
    ------------------------------------------------
    根据你的表自己写对应的Update和Delete语句就得啦!
      

  8.   

    关注,怎样更改无主键的dataset?