2010-07-27 59 views
0

我需要打开与SQL数据库的连接并读取表的子集,并在存在的情况下更新记录,或者如果找不到则插入。有truoble更新有关在数据集中更新/插入数据表的问题

SqlConnection conn = new SqlConnection(ConnectionStrings.PgenIntranet.SqlClientConnectionString); 
         SqlDataAdapter indicators = new SqlDataAdapter(); 
         string sql = "SELECT * FROM BusinessApplications.tbl_WPI_Site_Indicators where Year = '" + year + 
      "' and Month = '" + month + "' and PlantId = " + site.ID; 

    indicators.SelectCommand = new SqlCommand(sql, conn); 
    SqlCommandBuilder cb = new SqlCommandBuilder(indicators); 
    indicators.UpdateCommand = cb.GetUpdateCommand(); 
    DataSet ds = new DataSet(); 
    indicators.Fill(ds, "indtable"); 
    DataTable indtable = ds.Tables["indtable"]; 
    // this logic not working 
     if (indtable.Rows.Count == 0) { indtable.NewRow(); } 
     DataRow dr = indtable.NewRow(); 

    /// not sure how to make this work 
     indtable[1]["PlantId"] = site.ID; 
     dr["PlantId"] = site.ID; 

回答

0

这已经有一段时间,因为我用数据集/数据表/数据行,但我认为你靠近。如果我没记错的话,你需要创建一个新的行对象像你这样在这里:

DataRow dr = indtable.NewRow(); 

然后填充该行与您的数据,也类似于你如何在做它:

dr["PlantId"] = site.ID; 

然后最后将该行添加到DataTable中的行集合中。 (你要仔细检查DataTable实例是否实际上是DataSet的Tables集合中的DataTable,我不记得具体情况。直接引用Tables集合可能更安全,而不是直接引用它们对象)。

请注意,这不是而是将行添加回数据库。它只是将它添加到DataTable实例。您需要相应地更新回数据库。你在这里的设置有点......凌乱......所以我没有快速的答案。既然你只是使用普通的旧ADO,那么我想你需要创建一个更新命令并填充它并相应地在连接上运行它。

在这样做时,请注意修复SQL注入漏洞就像你有一个有:)

+0

我没有被绑在这个老的ADO上,你有什么建议吗? – BillTetrault 2010-07-27 19:33:46

+0

@Bill NHibernate和实体框架都是ORM的,很受欢迎,并且有很多的宣传。见http://stackoverflow.com/questions/3251849/please-recommend-net-orm-for-n-tier-development – 2010-07-27 19:49:59

0

不要忘了你的新行添加到表中,然后调用更新...

indtable.Rows.Add(dr); 
ds.Update();