【问题标题】:Improving data access class [closed]改进数据访问类[关闭]
【发布时间】:2012-04-13 09:35:26
【问题描述】:

几年前,我们(作为一家公司)面临着让我们的开发人员停止编写经典的 ASP 页面并切换到 .net(并转而使用 system.data 进行数据访问)的情况。

作为一种所谓的“短期”措施,我编写了以下类,以使那些不习惯 system.data 及其所有新对象的人更容易切换:

http://www.heavencore.co.uk/forum/viewthread.php?thread_id=185

这个类的主要目的是使用法尽可能与经典 asp 相似并保持用法非常简单(加上添加电子邮件警报以防止错误捕获 yada yada yada):

Public db As New SimpleDataAccess
Public RS As New DataTable

ConnectDatabase()
db.Execute_Query(RS, "SELECT * FROM whatever WHERE IntColumn = " & tools.parseint(EmployeeID, 0) & " or TextColumn = '" & db,Escape("bla'blabla") & "' ORDER BY IntColumn")
For Each DB_Row As DataRow In RS.Rows
    response.Write(DB_Row("IntColumn"))
Next
CloseDatabase()

现在,这门课很烂的两个主要原因:

  • Sql 注入的东西(解析和引号转义)必须在类外完成 - 容易健忘 - 这里肯定需要引入参数化查询!
  • CloseDatabase() 必须在页面末尾手动调用 - 这通常会被遗忘,并且与服务器的连接保持打开状态 - 即使在页面完成渲染等之后也是如此

这门课很好的原因:

  • 该类的使用非常简单,可以非常轻松地将旧的经典 asp 代码转换为 .net
  • 查询和连接错误的电子邮件警报在课程本身中以不可见的方式处理
  • 它已经完美运行了 2 年多,没有任何问题

我的问题:

是否有任何其他类/建议可以让我替换此类但保留非常简单的用法,或者修改 Execute_Query() 和 Execute_NonQuery() 方法以处理参数化查询的最佳方法是什么?

简单是关键!

PS: 哪里是发布大量代码以用于 SO 问题的好地方? Pastebin 等只能保存一个月...

【问题讨论】:

    标签: asp.net sql-server vb.net tsql ado.net


    【解决方案1】:

    我认为this 可能会对您有所帮助。一大块代码。这几乎可以处理您需要的所有事情。您可以在数组中传递参数。也可以与存储过程一起使用。无需担心连接关闭。

    希望这会有所帮助。

    【讨论】:

    • Cheers Kaf,我注意到这是一个非常旧的版本(.net 1.1?) - 虽然我刚刚发现了这个相关问题:stackoverflow.com/questions/1050106/sqlhelper-class - 我目前正在调查现代等价物是什么。
    • 你可以把它做成一个最新版本的DLL。或者如果你谷歌,也许也可以下载。此外,您可以将其包装在一个小类中(在其中设置连接字符串)以避免每次连接数据库时都传递连接字符串。祝你好运!
    【解决方案2】:

    我一直使用来自http://www.fmstocks.com/(Asp Classic MS 应用程序示例)的函数。它非常简单,并且可以使用参数

    示例用法:

    set rs = RunSQLReturnRs("Select * from Usuario where UsuarioID = ?", _
                            array(mp("@UsuarioID", adInteger, 0, UsuarioID)))
    If not rs.eof then
        UsuarioName = rs("FullName")
    end if 
    

    DbHelper.ASP 完整代码(多年来略有修改)

    <!--#include file="../bus/adovbs.inc"-->
    <%
    Function GetConnectionString()
        GetConnectionString = "file name=c:\udl\miconnstring.udl"
    End Function
    
    Function mp(PName , PType , PSize, PValue)
        mp = Array(PName, PType, PSize, PValue)
    End Function
    
    Function RunSPReturnRS(strSP, params())
        On Error Resume next
    
        ' Create the ADO objects
        Dim rs , cmd
        Set rs = server.createobject("ADODB.Recordset")
        Set cmd = server.createobject("ADODB.Command")
    
        ' Init the ADO objects  & the stored proc parameters
        cmd.ActiveConnection = GetConnectionString()
        cmd.CommandText = strSP
        cmd.CommandType = adCmdStoredProc
        cmd.CommandTimeout = 900 ' 15 minutos
    
        collectParams cmd, params
    
        ' Execute the query for readonly
        rs.CursorLocation = adUseClient
        rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
    
        If err.number > 0 then
            BuildErrorMessage()
            exit function
        end if
    
        ' Disconnect the recordset
        Set cmd.ActiveConnection = Nothing
        Set cmd = Nothing
        Set rs.ActiveConnection = Nothing
    
        ' Return the resultant recordset
        Set RunSPReturnRS = rs
    
    End Function
    
    Function RunSP(strSP , params())
        On Error resume next
    
        ' Create the ADO objects
        Dim cmd
        Set cmd = server.createobject("ADODB.Command")
    
        ' Init the ADO objects & the stored proc parameters
        cmd.ActiveConnection = GetConnectionString()
        cmd.CommandText = strSP
        cmd.CommandType = adCmdStoredProc
        cmd.CommandTimeout = 900 ' 15 minutos
        collectParams cmd, params
    
        ' Execute the query without returning a recordset
        cmd.Execute , , adExecuteNoRecords
        If err.number > 0 then
            BuildErrorMessage()
            exit function
        end if
    
    
        ' Disconnect the recordset and clean up
        Set cmd.ActiveConnection = Nothing
        Set cmd = Nothing
    
        Exit Function
    
    End Function
    
    Function RunSQL(strSP , params())
        On Error resume next
    
        ' Create the ADO objects
        Dim cmd
        Set cmd = server.createobject("ADODB.Command")
    
        ' Init the ADO objects & the stored proc parameters
        cmd.ActiveConnection = GetConnectionString()
        cmd.CommandText = strSP
        cmd.CommandType = adCmdText
        cmd.CommandTimeout = 900 ' 15 minutos
        collectParams cmd, params
    
        ' Execute the query without returning a recordset
        cmd.Execute , , adExecuteNoRecords
        If err.number > 0 then
            BuildErrorMessage()
            exit function
        end if
    
        ' Cleanup
        Set cmd.ActiveConnection = Nothing
        Set cmd = Nothing
    
        Exit Function
    
    End Function
    
    Function RunSQLReturnRS(sqlstmt, params())
        On Error Resume next
    
        ' Create the ADO objects
        Dim rs , cmd
        Set rs = server.createobject("ADODB.Recordset")
        Set cmd = server.createobject("ADODB.Command")
    
        ' Init the ADO objects  & the stored proc parameters
        cmd.ActiveConnection = GetConnectionString()
        cmd.CommandText = sqlstmt
        cmd.CommandType = adCmdText
        cmd.CommandTimeout = 900 ' 15 minutos
    
        collectParams cmd, params
    
        ' Execute the query for readonly
        rs.CursorLocation = adUseClient
        rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
        If err.number > 0 then
            BuildErrorMessage()
            exit function
        end if
    
        ' Disconnect the recordset
        Set cmd.ActiveConnection = Nothing
        Set cmd = Nothing
        Set rs.ActiveConnection = Nothing
    
        ' Return the resultant recordset
        Set RunSQLReturnRS = rs
    
    End Function
    
    
    Function RunSPReturnInteger(strSP , params())
        On Error resume next
    
        ' Create the ADO objects
        Dim cmd
        Set cmd = server.createobject("ADODB.Command")
    
        ' Init the ADO objects & the stored proc parameters
        cmd.ActiveConnection = GetConnectionString()
        cmd.CommandText = strSP
        cmd.CommandType = adCmdStoredProc
        cmd.CommandTimeout = 900 ' 15 minutos
        collectParams cmd, params
    
        ' Assume the last parameter is outgoing
        cmd.Parameters.Append cmd.CreateParameter("@retval", adInteger, adParamOutput, 4)
    
        ' Execute without a resulting recordset and pull out the "return value" parameter
        cmd.Execute , , adExecuteNoRecords
        If err.number > 0 then
            BuildErrorMessage()
            exit function
        end if
        RunSPReturnInteger = cmd.Parameters("@retval").Value
    
        ' Disconnect the recordset, and clean up
        Set cmd.ActiveConnection = Nothing
        Set cmd = Nothing
    
        Exit Function
    End Function
    
    Private Sub collectParams(cmd , argparams())
        Dim params , v
        Dim i , l , u
    
        params = argparams
    
    
        For i = LBound(params) To UBound(params)
            l = LBound(params(i))
            u = UBound(params(i))
    
            ' Check for nulls.
            If u - l = 3 Then
                If VarType(params(i)(3)) = vbString Then
                    If params(i)(3) = "" then
                        v = null
                    else
                        v = params(i)(3)
                    end if
                Else
                    v = params(i)(3)
                End If
    
                If params(i)(1) = adLongVarChar Then
                    Dim p 'As New Parameter
                    Set p = cmd.CreateParameter(params(i)(0), params(i)(1), adParamInput)
                    p.Attributes = adParamLong + adParamSigned
                    If Not IsNull(v) Then
                        'Seteo para text columns is not null
                        p.AppendChunk v
                        p.Size = Len(v)
                    Else
                        'Seteo para text columns is null
                        p.Value = v
                        p.Size = 10000
                    End If
                    cmd.Parameters.Append p
                Else
                    cmd.Parameters.Append cmd.CreateParameter(params(i)(0), params(i)(1), adParamInput, params(i)(2), v)
                End If
            Else
                RaiseError m_modName, "collectParams(...): incorrect # of parameters"
            End If
        Next
    End Sub
    
    %>
    

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 2011-10-25
      • 2012-03-18
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多