• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

根据多个条件参数化查询一个记录集的ASP数据库操作函数

asp 海叔叔 4年前 (2021-05-31) 59次浏览 已收录 0个评论

关键词
参数化查询 多个字段 记录集 ASP函数

摘要

本文介绍一个ASP操作数据库的函数,它可以直接通过多个条件参数化查询一个记录集。因为是参数化查询,所以这个函数很安全,不会有SQL注入。

这个ASP操作数据库的具体内容如下:

'获取数据库信息,N个结果字段,N个条件
Function GetDbDataNN(conn,rs,sql,whereState,whereArray)
    Dim cmdT,i
    Set cmdT=Server.CreateObject("ADODB.Command")
    If conn.state<>1 Then conn.open
    With cmdT    
    Set .ActiveConnection = conn
    .CommandType = 1
    .CommandText = sql & " where 1=1 " & whereState
    For i=1 To UBound(whereArray)
        If whereArray(i,2) = "int" Then
            .Parameters.Append .CreateParameter(whereArray(i,1),3,1,4,whereArray(i,3))
        Else
            .Parameters.Append .CreateParameter(whereArray(i,1),200,1,128,whereArray(i,3))
        End If
    Next
    set rs=.Execute()
    End With
    Set cmdT.ActiveConnection = Nothing
    set cmdT=Nothing
End Function

解释一下GetDbDataNN这几个参数的含义:
conn:数据库连接
rs:记录集
sql:sql语句
whereState:条件语句,函数中在Where之后默认已经加了1=1的条件,所以whereState里面直接使用 “and 字段1=值1 and 字段2=值2”的格式即可。
whereArray:条件的值,以一个数组的形式传递值,这是一个二维数组,第一维表示参数的个数,第二维有三个值,分别表示参数名,参数类型,参数值。

函数的返回值
函数没有返回值,rs作为传入参数,也作为输出参数。

使用举例:
如果有一个用户表(表名为tb_user),有user_id、user_name、user_right、user_1、user_2等多个字段。这时我想通过user_1、user_2来获取整条记录,可以怎么通过这个asp数据库操作函数来实现呢?

'--------------调用示例-------------------------
'
'Dim whereState : whereState = ""
'ReDim whereArray(0,3)
'Dim whereCount : whereCount = 0
'
'If user_1<>"" Then
'    whereCount = whereCount + 1
'    whereState= whereState & " and user_1=?"
'    ReDim Preserve whereArray(whereCount,3)
'    whereArray(whereCount,1) = "user_1" : whereArray(whereCount,2) = "varchar" : whereArray(whereCount,3) = user_1
'End If
'If user_2<>"" Then
'    whereCount = whereCount + 1
'    whereState= whereState & " and user_2=?"
'    ReDim Preserve whereArray(whereCount,3)
'    whereArray(whereCount,1) = "user_2" : whereArray(whereCount,2) = "varchar" : whereArray(whereCount,3) = user_2
'End If
'
'conn.open
'sql="select * from tb_user"
'set rs = Server.CreateObject("ADODB.Recordset")
'Call GetDbDataNN(conn,rs,sql,whereState,whereArray)
'Do While Not rs.EOF
'...
'    rs.MoveNext
'Loop
'rs.Close: Conn.Close

关于根据多个条件参数化查询一个记录集的ASP数据库操作函数,本文就介绍这么多,希望对您有所帮助,谢谢!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:根据多个条件参数化查询一个记录集的ASP数据库操作函数
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址