每次我有新插入时,我在Visual Basic中都有此代码:
Private _conn As SqlConnection
Public Function Include(ByVal pSql As String, Optional timeout As Integer = 120) As Boolean
Try
Dim SQL_Str = "my string of conection... with database. not put on this example"
_conn = New SqlConnection(SQL_Str)
_conn.Open()
_adapter = New SqlDataAdapter
cmd.CommandTimeout = timeout
cmd.Connection = _conn
cmd.CommandText = pSql
cmd.CommandType = CommandType.Text
_adapter.InsertCommand = cmd
_adapter.InsertCommand.ExecuteNonQuery()
Catch ex As Exception
InputBox("New Error on Sql cmd: ", , pSql)
End Try
_conn.Close()
_conn.Dispose()
_conn = Nothing
_adapter.Dispose()
_adapter = Nothing
End Function
好吧,这是更新数据库的直接方法。
但是假设我同时拥有1000个连接,应用程序是否支持这种方法?
此方法是否支持同时访问_conn对象的线程?
是否真的需要创建一个连接池来处理数据?
连接池真的可以改善某些地方吗?
例如这样我就使应用程序而不是数据库过载了?
如果是这样,我将如何在VbNet / Visual Basic上做到这一点?
答案 0 :(得分:2)
是,池连接确实更快。它们使您无需不断重新协商登录名和协议信息。甚至更好的是,它已经内置在SqlConnection
类型中,并且以合理的线程安全方式完成(现有代码为 not )。
简短的版本是您确实希望为大多数查询创建一个全新的连接对象,并且不希望尝试在整个应用程序或会话中共享相同的连接变量。
>鉴于此,我在该代码中看到了几个大问题:
_conn
变量当作本地变量来处理,从而无法在线程之间安全地共享此类的实例。Finally
或Using
块,则没有清除连接的机制。仅在Catch
之后关闭是不够的。您想要更多类似这样的东西:
Private cnString As String = "my string of conection... with database. not put on this example"
Public Sub Include(pSql As String, parameters() As SqlParamter, Optional timeout As Integer = 120)
Using conn As New SqlConnectioN(cnString), _
cmd As New SqlCommand(pSql, conn)
If parameters IsNot Nothing AndAlso parameters.Length > 0 Then
cmd.Parameters.AddRange(parameters)
End If
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
您可能会这样称呼(假设类型或实例名称为DB
):
Dim pSql As String = "INSERT INTO [ExampleTable] (FirstName, LastName, CreationDate) VALUES (@FirstName, @LastName, @CreationDate)"
Dim parameters = {
New SqlParameter("@FirstName", SqlDbType.NVarChar, 20),
New SqlParameter("@LastName", SqlDbType.NVarChar, 20),
New SqlParameter("@CreationDate", SqlDbType.DateTime)
}
parameters(0).Value = "John"
parameters(1).Value = "Smith"
parameters(2).Value = DateTime.Now
Try
DB.Include(pSql, parameters)
Catch ex As Exception
MessageBox.Show(String.Format("New Error on Sql cmd:{0}{1}{0}{0}Message:{2}",vbCrLf, pSql, ex.Message)
End Try