處理在執(zhí)行數(shù)據(jù)庫查詢中的特殊字符的問題
發(fā)表時間:2024-06-10 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]在進(jìn)行數(shù)據(jù)庫的查詢時,會經(jīng)常遇到這樣的情況: 例如想在一個用戶數(shù)據(jù)庫中查詢他的用戶名和他的密碼, 但恰好該用戶使用的名字和密碼中有特殊的字符,例如單引號,“ ”號 雙引號或者連字符“&” 例如他的名字是1'test,密碼是A &900 這時當(dāng)你執(zhí)行以下的查詢語句時,肯定會抱...
在進(jìn)行數(shù)據(jù)庫的查詢時,會經(jīng)常遇到這樣的情況:
例如想在一個用戶數(shù)據(jù)庫中查詢他的用戶名和他的密碼,
但恰好該用戶使用的名字和密碼中有特殊的字符,例如單引號,“ ”號
雙引號或者連字符“&”
例如他的名字是1'test,密碼是A &900
這時當(dāng)你執(zhí)行以下的查詢語句時,肯定會抱錯:
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中," "為分割字段用的,顯然會出錯了,F(xiàn)在提供下面的幾個函數(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
有了上面幾個函數(shù)后,當(dāng)你在執(zhí)行一個sql前,請先使用
SQL = "SELECT * FROM SecurityLevel WHERE UID='" & SQLFixup(UserID) & "'"
SQL = SQL & " AND PWD='" & SQLFixup(Password) & "'" (出處:熱點網(wǎng)絡(luò))