简体   繁体   English

使用类连接到SQL Server数据库是否可以?

[英]IS it OK to use a class for connecting to my SQL Server database?

I have a public class called dbOPS that has some subs and functions like: 我有一个名为dbOPS的公共类,它具有一些子功能,例如:

 Public Function getSqlReader(ByVal sql As String) As SqlDataReader
    Dim cmd As New SqlCommand(sql, getConn)
    cmd.CommandTimeout = 360
    Dim dr As SqlDataReader = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)

    Return dr
End Function

Public Function getSqlScalar(ByVal sql As String)
    Dim cmd As New SqlCommand(sql, getConn)
    cmd.CommandTimeout = 360
    Dim cnt = cmd.ExecuteScalar
    closeCX()
    Return cnt
End Function

Public Sub ExecuteSql(ByVal sql As String)
    Dim cmd As New SqlCommand(sql, getConn)
    cmd.CommandTimeout = 360
    cmd.ExecuteNonQuery()
    closeCX()
End Sub

I then use the following command once per page and use the db variable many (many) times throughout the page: 然后,我每页使用一次以下命令,并在整个页面中多次(多次)使用db变量:

Dim db as new dbOPS

Recently, I have started getting many errors 最近,我开始出现很多错误

ExecuteScalar requires an open and available connection. ExecuteScalar需要打开且可用的连接。 the connection's current state is connecting 连接的当前状态为连接

Is this the cause? 这是原因吗?

Is there any way around it without rewriting every page and every command to open its own connection? 有什么办法可以解决,而不必重写每个页面和每个命令来打开自己的连接?

Thanks 谢谢

It's probably best to detect the connection and reopen them just in case it is not open prior to executing the command. 最好是在执行命令之前检测连接并重新打开它们,以防万一它没有打开。

If (cmd.Connection.State != ConnectionState.Open) Then
    cmd.Connection.Open()

Do this as part of your helper methods. 将此作为您的辅助方法的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM