2016-05-12 27 views
0

在数据源()后执行一个代码后面的数据源和/或连接需要关闭吗?我的代码是vb.net数据源和连接背后的代码需要在使用后关闭吗?

Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultDataBaseServer").ConnectionString) 
    conn.Open() 
    Dim sql As String = lblConcept.Text.Replace("@xxxxxx", xxxxxID.Value) 
    Dim myCommand As SqlCommand = New SqlCommand(sql, conn) 
    ckConceptList.DataSource = myCommand.ExecuteReader() 
    ckConceptList.DataBind() 

回答

1

你应该使用try catch,最后。

try 
Dim conn As SqlConnection = New SqlConnection (System.Configuration.ConfigurationManager.ConnectionStrings("DefaultDataBaseServer").ConnectionString) 
conn.Open() 
Dim sql As String = lblConcept.Text.Replace("@xxxxxx", xxxxxID.Value) 
Dim myCommand As SqlCommand = New SqlCommand(sql, conn) 
ckConceptList.DataSource = myCommand.ExecuteReader() 
ckConceptList.DataBind() 


Catch ex As Exception 

Finally 
     If pConn.State = ConnectionState.Open Then 
      pConn.Close() 
     End If 
    End Try 
3

does a code behind datasource and/or a connection need to be closed after databind()

术语“代码背后”和的DataBind()暗示,这是关系到一些网络技术,但有任何的arent这样的标签。

但是,通常情况下,任何具有Dispose()方法的方法都表示它可能会在引擎盖下分配一些资源,这些资源不仅应该关闭,还应该配备Disposed以释放这些资源。

图形对象像笔,画笔和位图不会丢弃可能会(最终!)最终引发臭名昭着的“GDI +中的通用错误”异常。但是,诸如Connections和Command对象之类的数据库对象不会导致您的应用程序泄漏。 This questionFor Loop中创建新的DBCommand对象而不处理它们,并遇到超出系统资源的异常。

NET Using blocks(在C#中为using())可以简化关闭和处理这些事情。下面还将展示如何在SQL中使用的参数,而不是String.Replace()

Dim SQL = "SELECT a, b, c FROM SomeTable WHERE Foo = @name" 
Dim dt As New DataTable 
Using dbcon As New MySqlConnection(MySQLConnStr) 
    Using cmd As New MySqlCommand(sql, dbcon) 

     cmd.Parameters.Add("@name", MySqlDbType.Text).Value = lblConcept.Text 

     dbcon.Open() 
     dt.Load(cmd.ExecuteReader()) 
     dgv2.DataSource = dt 
    End Using   ' dispose of cmd 
End Using    ' dispose of dbcon 
  • 不会与string.replace防止如嵌入式蜱即使是简单的事情,在Carol's Cookie Shoppe
  • Parameters.Add()允许您指定数据类型和避免数据类型错误时将其留到VB猜测

Using声明(Dim)一个新的变量并初始化,所以不可能有超视距er dbConcmd变量在相同的范围内。它还会创建一个新的块范围:这些目标变量和其中声明的任何内容都将在该块的本地。上面声明了块外的数据表,所以它可以在其他地方使用。可以叠加或组合Using s到降低像这样缩进:

Using dbcon As New MySqlConnection(MySQLConnStr), 
    cmd As New MySqlCommand(sql, dbcon) 

    dbcon.Open() 
    dt.Load(cmd.ExecuteReader()) 
    dgv2.DataSource = dt 

End Using 

的VB编辑器是一个有点古怪有关 - 智能感知不会与dbcon可变参数帮助cmd直到完成并关闭块。

的更多信息:

Connection Pooling介绍NET如何最大限度地减少创建DBConnections的成本。

Using Statement (Visual Basic)。从中,引用:

有时您的代码需要非托管资源,例如文件句柄,COM包装器或SQL连接。使用块可以保证在您的代码完成后处置一个或多个这样的资源。这使它们可供其他代码使用。

IDisposable(通常)的Dispose方法的实现方式。备注值得一读。

Avoiding Problems with the Using Statement解释了原因和一个Try/Catch块与Using声明相结合的wherefores。这里也有大量的帖子描述了如何在各种情况下使用这两者。

How do I create a parameterized SQL query? Why Should I?

相关问题