在進(jìn)行數(shù)據(jù)庫的查詢時(shí),會(huì)經(jīng)常遇到這樣的情況:
例如想在一個(gè)用戶數(shù)據(jù)庫中查詢他的用戶名和他的密碼,但恰好該用戶使用的名字和密碼中有特殊的字符,例如單引號(hào),“|”號(hào),雙引號(hào)或者連字符“&”。
例如他的名字是1"test,密碼是A|&900
這時(shí)當(dāng)你執(zhí)行以下的查詢語句時(shí),肯定會(huì)報(bào)錯(cuò):
SQL = "SELECT * FROM SecurityLevel WHERE UID="" & UserID & """
SQL = SQL & " AND PWD="" & Password & """
因?yàn)槟愕腟QL將會(huì)是這樣:
SELECT * FROM SecurityLevel WHERE UID="1"test" AND PWD="A|&900"
在SQL中,"|"為分割字段用的,顯然會(huì)出錯(cuò)了?,F(xiàn)在提供下面的幾個(gè)函數(shù) 專門用來處理這些頭疼的東西:
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
有了上面幾個(gè)函數(shù)后,當(dāng)你在執(zhí)行一個(gè)sql前,請先使用
SQL = "SELECT * FROM SecurityLevel WHERE UID="" & SQLFixup(UserID) & """
SQL = SQL & " AND PWD="" & SQLFixup(Password) & """
該文章在 2011/4/13 15:07:39 編輯過