Author: csbq
When querying the database, you will often encounter the following situation:
For example, you want to query his user name and his password in a user database, but the name and password used by the user happen to have special characters, such as single quotes, "|" signs, double quotes or hyphens "&".
For example, his name is 1'test and his password is A|&900. When you execute the following query statement, an error will definitely be reported:
SQL = "SELECT * FROM SecurityLevel WHERE UID='" & UserID & "'"
SQL = SQL & " AND PWD='" & Password & "'"
because your SQL will be like this:
SELECT * FROM SecurityLevel WHERE UID='1'test' AND PWD='A|&900'
In SQL, "|" is used to separate fields, so something will obviously go wrong. The following functions are now provided to deal with these headaches:
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
After having the above functions, before you execute a sql, please use:
SQL = "SELECT * FROM SecurityLevel WHERE UID='" & SQLFixup(UserID) & "'"
SQL = SQL & " AND PWD='" & SQLFixup(Password) & "'"