在ADO.NET中进行更新之前是否需要执行填充?

时间:2011-09-09 22:41:10

标签: c# ado.net fill

这看似微不足道,但我见过的每个ADO.net示例在“更新”之前几乎总是有“填充”。我们真的不想填充可能有1000个blob的数据集,我们只想添加(插入)到表中。是否需要填写更新?作为示例,这里是来自MSFT网站的示例代码(我们正在做类似的事情):

SqlConnection con = new SqlConnection("Server=Darkover;uid=<username>;pwd=<strong            password>;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da); // What does this even do?
DataSet ds = new DataSet("MyImages");

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(@"C:\winnt\Gone Fishing.BMP", FileMode.OpenOrCreate, FileAccess.Read);

byte[] MyData= new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

fs.Close();

da.Fill(ds,"MyImages");  // are they really filling a dataset with all those images???

DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();

myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");

con.Close();

1 个答案:

答案 0 :(得分:0)

您希望调用da.Fill()以获取MyImages表的架构。这样,在为列分配值时,您可以使用DataRow调用返回的NewRow()和正确的架构(列,键等)。

您可以通过设置SqlDataAdapter告诉SqlDataAdapter.FillCommandBehavior仅返回没有数据的架构:

da.FillCommandBehavior = CommandBehavior.SchemaOnly;
da.Fill(ds,"MyImages"); // Just get the schema for MyImages

DataRow myRow = ds.Tables["MyImages"].NewRow();
myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);

da.Update(ds, "MyImages");

如果您的查询返回多个表,您也可以使用da.FillSchema(),使用单个DataTableDataSet

DataTable dt = new DataTable();

da.FillSchema(dt, SchemaType.Mapped);

DataRow myRow = dt.NewRow();
myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
dt.Rows.Add(myRow);

da.Update(dt);