C# DataAdapter不需要打开数据库连接?
我尝试在C#net中使用DataAdapter。但我仍然不了解DataAdapter的一些内容 我读了很多关于DataAdapter和DataReader的文章和博客 我知道DataAdapter将在需要时自动打开和关闭数据库 但是, 当我运行上面的代码时,会收到一条错误消息,上面写着“连接必须打开” 为什么适配器不能自动打开连接 并且,我想使用insertCommand插入数据(对于此测试,我打开了连接) 许多示例使用Adapter.Update(),但对我来说,它不起作用:( 没有错误,也没有插入任何内容 使用da.InsertCommand.ExecuteNonQuery();而不是Update(),它可以工作 我做错了什么 谢谢!这么说 Fill方法隐式打开DataAdapter连接 如果发现连接尚未打开,则正在使用。如果 填充打开的连接时,也会关闭连接 填充完成。这可以简化处理 单个操作,如填充或更新 这意味着在C# DataAdapter不需要打开数据库连接?,c#,asp.net,dataadapter,advantage-database-server,C#,Asp.net,Dataadapter,Advantage Database Server,我尝试在C#net中使用DataAdapter。但我仍然不了解DataAdapter的一些内容 我读了很多关于DataAdapter和DataReader的文章和博客 我知道DataAdapter将在需要时自动打开和关闭数据库 但是, 当我运行上面的代码时,会收到一条错误消息,上面写着“连接必须打开” 为什么适配器不能自动打开连接 并且,我想使用insertCommand插入数据(对于此测试,我打开了连接) 许多示例使用Adapter.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
OP已经对连接打开代码进行了注释。它应该是注释。@PankajGarg这正是OP代码失败的原因。我的理解是,当您发现错误时,您会发布一个答案。感谢您的回答!在填充数据集后,连接将关闭,因此在此之后,如果我们需要更新数据库,请e需要手动打开和关闭连接,对吗?你知道第二个问题吗?我不知道你的命令顺序。根据上面的代码,你应该在填充之前打开连接,然后在填充之后关闭。如果使用
语句,效果更好。我将用一些伪代码更新我的答案。你还知道如何使用da.Insert吗Command=新AdsCommand()也是?:)
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.
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