ASP中執行資料庫查詢中的特殊字元的問題
來源:互聯網
上載者:User
資料|資料庫|問題|執行 在進行資料庫的查詢時,會經常遇到這樣的情況:
例如想在一個使用者資料庫中查詢他的使用者名稱和他的密碼,但恰好該使用者使用的名字和密碼中有特殊的字元,例如單引號,“|”號
雙引號或者連字號“&”。
例如他的名字是1'test,密碼是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) & "'"