明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

處理在執(zhí)行數(shù)據(jù)庫(kù)查詢中的特殊字符的問(wèn)題

[摘要]在進(jìn)行數(shù)據(jù)庫(kù)的查詢時(shí),會(huì)經(jīng)常遇到這樣的情況: 例如想在一個(gè)用戶數(shù)據(jù)庫(kù)中查詢他的用戶名和他的密碼, 但恰好該用戶使用的名字和密碼中有特殊的字符,例如單引號(hào),“ ”號(hào) 雙引號(hào)或者連字符“&” 例如他的名字是1'test,密碼是A &900 這時(shí)當(dāng)你執(zhí)行以下的查詢語(yǔ)句時(shí),肯定會(huì)抱...

在進(jìn)行數(shù)據(jù)庫(kù)的查詢時(shí),會(huì)經(jīng)常遇到這樣的情況:
例如想在一個(gè)用戶數(shù)據(jù)庫(kù)中查詢他的用戶名和他的密碼,
但恰好該用戶使用的名字和密碼中有特殊的字符,例如單引號(hào),“ ”號(hào)
雙引號(hào)或者連字符“&”
例如他的名字是1'test,密碼是A &900
這時(shí)當(dāng)你執(zhí)行以下的查詢語(yǔ)句時(shí),肯定會(huì)抱錯(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ù)
專(zhuān)門(mén)用來(lái)處理這些頭疼的東西:

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前,請(qǐng)先使用
SQL = "SELECT * FROM SecurityLevel WHERE UID='" & SQLFixup(UserID) & "'"
SQL = SQL & " AND PWD='" & SQLFixup(Password) & "'" (出處:熱點(diǎn)網(wǎng)絡(luò))