开发者

Question on updating/inserting a datatable in a dataset

I need to open a connection to SQL database and read a subset of a table and either update a record if exists or insert if not found. Having truoble updating

    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;


It's been a while since I've used DataSets/DataTables/DataRows, but I think you're close. If I remember correctly, you'll need to create a new row object like you do here:

DataRow dr = indtable.NewRow();

Then populate that row with your data, also similar to how you were doing it:

dr["PlantId"] = site.ID;

Then finally add that row to the rows collection in the DataTable. (You'll want to double-check if your DataTable instance is actually the DataTable in the Tables collection on the DataSet, I don't recall the specifics. It may be safer to reference the Tables collection directly rather than put it in its own object.)

Note that this does not add the row back to the database. It just adds it to the DataTable instance. You'll need to update back to the database accordingly. And this setup that you have here is a bit... messy... so I have no quick answer for that. Since you're just using plain old ADO then I guess you'll need to create an update command and populate it and run it against the connection accordingly.

In doing so, please take care to fix SQL injection vulnerabilities like the one you have there :)


Don't forget to add your new row to the table, then call update...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜