gpt4 book ai didi

c# - DataAdapter 不需要打开数据库连接?

转载 作者:太空狗 更新时间:2023-10-29 20:59:20 24 4
gpt4 key购买 nike

我尝试在 C#.net 中使用 DataAdapter。但我仍然不了解 DataAdapter。

我阅读了很多关于 DataAdapter 和 DataReader 的文章和博客。

我知道 DataAdapter 会在需要时自动打开和关闭数据库。

但是,

//conn.Open();
AdsDataAdapter da;
da = new AdsDataAdapter("Select * from Test", conn);
AdsCommandBuilder cb;
cb = new AdsCommandBuilder(da);

DataSet ds = new DataSet();
da.Fill(ds, "Test");

DataRow newrow = ds.Tables["Test"].NewRow();
newrow["Name"] = "How about";
ds.Tables["Test"].Rows.Add(newrow);
da.Update(ds, "Test");

当我运行上面的代码时,我收到一条错误消息,指出“连接必须打开。”

为什么适配器不能自动打开连接?

并且,我想使用 insertCommand 插入数据(对于此测试,我打开了连接)。

da.InsertCommand = new AdsCommand("INSERT INTO test (NAME) values('Insert Test #1')", conn);
//da.InsertCommand.ExecuteNonQuery(); // it works
da.Update(ds,"Test"); //but it does not works.

许多使用 Adapter.Update() 的示例,但对我来说,它不起作用:(

没有错误,也没有插入任何内容。

并使用 da.InsertCommand.ExecuteNonQuery();而不是 Update(),它有效。

我做错了什么?

谢谢!

最佳答案

MSDN说是

The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it will also close the connection when Fill is finished. This can simplify your code when dealing with a single operation such as a Fill or an Update.

这意味着在 da.Fill(ds, "Test"); 之后,您的连接将由方法本身关闭。但是您需要为以下更新打开它(并且失败)

编辑:从您上面的代码派生的伪代码

using(AdsConnection com = new AdsConnection(connectionString));
{
conn.Open();
using(AdsDataAdapter da = new AdsDataAdapter("Select * from Test", conn))
{
AdsCommandBuilder cb = new AdsCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "Test");

// Now the connection is still open and you can issue other commands

DataRow newrow = ds.Tables["Test"].NewRow();
newrow["Name"] = "How about";
ds.Tables["Test"].Rows.Add(newrow);

// da.Update should work here. No more connection closed.
da.Update(ds, "Test");
}
} // Exiting from the using block, the connection will be closed

关于c# - DataAdapter 不需要打开数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com