【问题标题】:DataAdapter does not need to make db connection open?DataAdapter 不需要打开数据库连接?
【发布时间】:2012-04-26 14:06:41
【问题描述】:

我尝试在 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(),它可以工作。

我做错了什么?

谢谢!

【问题讨论】:

    标签: c# asp.net dataadapter advantage-database-server


    【解决方案1】:

    MSDN 这么说

    Fill 方法隐式打开 DataAdapter 的连接 如果发现连接尚未打开,则正在使用。如果 填写打开了连接,当它也会关闭连接 填充完成。这可以在处理 单个操作,例如填充或更新。

    这意味着在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
    

    【讨论】:

    • 连接打开代码已被 OP 注释掉。应该是评论。
    • @PankajGarg 这正是 OP 代码失败的原因。我的理解是,当您发现错误时,您会发布答案。
    • 感谢您的回答!填充到DataSet后连接将被关闭,那么之后,如果我们需要更新数据库,那么我们需要手动打开和关闭连接对吗?第二个问题你知道吗?
    • 我不知道你的命令顺序。从上面的代码中,您应该在填充之前打开连接并在之后关闭。如果using 声明更好。我会用一些伪代码更新我的答案。
    • 你也知道如何使用 da.InsertCommand = new AdsCommand() 吗? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多