您的位置:首页 > 数据库

DbDataAdapter 的Fill(DataTable dataTable) 和 Update(DataSet dataSet);方法的使用

2014-02-24 17:32 483 查看
DbDataAdapter 的Fill(DataTable dataTable) 和 Update(DataSet dataSet);方法的使用

方法定义:

public int Fill(DataTable dataTable);

在 System.Data.DataSet 的指定范围中添加或刷新行,以与使用 System.Data.DataTable 名称的数据源中的行匹配。

public override int Update(DataSet dataSet);

为指定 System.Data.DataTable 中每个已插入、已更新或已删除的行调用相应的 INSERT、UPDATE 或 DELETE 语句。

下面我们先使用Fill(DataTable dataTable);方法把数据从数据库中提取到DataSet中,数据修改之后,我们可以再使用Update方法,将我们对DataSet

中数据的修改提交至数据库.

示例代码如下

            DataSet ds = new DataSet();

            using (SqlConnection connection = new SqlConnection(PubConstant.ConnectionString))

            {

                try

                {

                    connection.Open();

                    SqlDataAdapter command = new SqlDataAdapter("SELECT * FROM [jarlinfowkk].[dbo].[oSensorData1]", connection);

                    command.Fill(ds);

                    DataTable table = ds.Tables[0];

                    int count = table.Rows.Count;

                    for (int s = 0; s < table.Columns.Count; s++)

                    {

                      

                        DataRow row = table.Rows[s];

                        DataRow newRow = table.NewRow();

                        for (int k = 0; k < table.Columns.Count - 1; k++)

                        {

                            newRow[k] = row[k];

                        }

                        DateTime dt = DateTime.Parse(row["pAcquisitionTime"].ToString());

                        newRow["pAcquisitionTime"] = dt.AddYears(3);

                        //修改 DataSet数据集

                        ds.Tables[0].Rows.Add(newRow);

                    }

                    //因为我们只是插入了数据,所以只需要生成InsertCommand,否则 还需要 UpdateCommand ,DeleteCommand

                    //由SqlCommandBuilder为我们生成 InsertCommand

                    SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(command);

                    command.InsertCommand = myCommandBuilder.GetInsertCommand();

                    command.Update(ds);

                    connection.Close();

                    MessageBox.Show("OK");

                }

                catch (System.Data.SqlClient.SqlException ex)

                {

                    throw new Exception(ex.Message);

                }

            }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息