SqlDataAdapter连接打开&关 [英] SqlDataAdapter Connection open & close

查看:74
本文介绍了SqlDataAdapter连接打开&关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=studinfo;Integrated Security=True"))
       {
          
           // Create new DataAdapter
           using (SqlDataAdapter a = new SqlDataAdapter(
               "SELECT * FROM Stud_Info", c))
           {
              
               DataTable t = new DataTable();
               a.Fill(t);

              
               GridView1.DataSource = t; // <-- From your designer
               GridView1.DataBind(); }}







以上代码工作得非常好,它还将数据绑定到gridview



问题: 谁将管理开放&在这里关闭连接

推荐答案

参考 - DbDataAdapter.Fill Method(DataTable) [ ^ ]。

Refer - DbDataAdapter.Fill Method (DataTable)[^].
Quote:

Fill方法使用由关联的SelectCommand属性指定的SELECT语句从数据源中检索行。与SELECT语句关联的连接对象必须有效,但不需要打开。如果在调用Fill之前关闭连接,则会打开它以检索数据,然后关闭。如果在调用Fill之前连接已打开,它将保持打开状态。

The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.


SqlConnection 对象本身负责处理它。您不必每次都明确管理此连接,即一旦您将数据库的连接字符串提供给代码,就可以在此处完成连接作业。

现在你必须通过查询或程序和东西来处理你的数据,以及你如何向用户显示,即在网格或列表视图中等。

如果你可能已经注意到,你不能继承这个SqlConncetion 类。

参见文档 [ ^ ]

所以你可以看到,它照顾自己。 :)



-KR
SqlConnection object itself takes care of it. You don't have to explicitly mange this connection every time, i.e Once you provide the Connenction String of your database to the code, connection job is done here.
Now you have to take care of your data by query or procedure and stuff and how you display to the user, i.e In Grid or in listview etc.
And if you might have noticed, you can't inherit this SqlConncetion class.
See the documentation[^]
So as you can see, it takes care itself. :)

-KR


这篇关于SqlDataAdapter连接打开&amp;关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆