数据库查询中的特殊字符的问题

数据库查询中的特殊字符的问题

在进行数据库的查询时,会常常遇到这种情况:
   比如想在一个用户数据库中查询他的username和他的password。但恰好该用户使用的名字和password中有特殊的字符。比如单引號,“|”号,双引號或者连字符“&”。


   比如他的名字是1"test,password是A|&900
   这时当你运行下面的查询语句时。肯定会报错:
SQL = "SELECT * FROM SecurityLevel WHERE UID="" & UserID & """
SQL = SQL & " AND PWD="" & Password & """ 
   由于你的SQL将会是这样:
SELECT * FROM SecurityLevel WHERE UID="1"test" AND PWD="A|&900" 
   在SQL中。"|"为切割字段用的,显然会出错了。如今提供以下的几个函数 专门用来处理这些头疼的东西:
Function ReplaceStr (TextIn, ByVal SearchStr As String, _
ByVal Replacement As String, _
ByVal CompMode As Integer)

 Dim WorkText As String, Pointer As Integer
  If IsNull(TextIn) Then
   ReplaceStr = Null
  Else
   WorkText = TextIn
   Pointer = InStr(1, WorkText, SearchStr, CompMode)
   Do While Pointer > 0
    WorkText = Left(WorkText, Pointer - 1) & Replacement & _
    Mid(WorkText, Pointer + Len(SearchStr))
    Pointer = InStr(Pointer + Len(Replacement), WorkText, SearchStr, CompMode)
   Loop
   ReplaceStr = WorkText
  End If
End Function

Function SQLFixup(TextIn)
  SQLFixup = ReplaceStr(TextIn, """, """", 0)
End Function
Function JetSQLFixup(TextIn)
  Dim Temp
  Temp = ReplaceStr(TextIn, """, """", 0)
  JetSQLFixup = ReplaceStr(Temp, "|", "" & chr(124) & "", 0)
End Function

Function FindFirstFixup(TextIn)
  Dim Temp
  Temp = ReplaceStr(TextIn, """, "" & chr(39) & "", 0)
  FindFirstFixup = ReplaceStr(Temp, "|", "" & chr(124) & "", 0)
End Function 
   有了上面几个函数后,当你在运行一个sql前。请先使用
SQL = "SELECT * FROM SecurityLevel WHERE UID="" & SQLFixup(UserID) & """
SQL = SQL & " AND PWD="" & SQLFixup(Password) & """。

本文完!

posted @ 2016-04-02 15:26  zfyouxi  阅读(568)  评论(0编辑  收藏  举报