Autore: Vito
Arconzo
Spesso non possiamo o
vogliamo utilizzare query parametriche. In queste situazioni utilizzo per avere
una semplicissima ma molto efficace funzione che ripulisce e normalizza in
valore da inserire in una query.
Public Shared Function SqlParameter(ByVal Value As Object) As String
Dim sql As String = String.Empty
If ((Value Is Nothing) OrElse (Value.GetType Is GetType(DBNull))) Then
Value = String.Empty
End If
If (Value.GetType Is GetType(String)) Then
Return ("'" & Value.ToString.Replace("'", "''") & "'")
End If
If (((((Value.GetType Is GetType(Decimal)) _
Or (Value.GetType Is GetType(Integer))) _
Or (Value.GetType Is GetType(Long))) _
Or (Value.GetType Is GetType(Short))) _
Or (Value.GetType Is GetType(Byte))) Then
Return Value.ToString.Replace(","c, "."c)
End If
Return sql
End Function
L'utilizzo
è semplicissimo:
Dim query As String = "SELECT * FROM clienti WHERE codice=" + SqlParameter(1)
Anche se questa funzione ripulisce il valore passato alla query, il NON utilizzare query parametriche è una tecnica che può causare problemi di SQL INJECTION e va quindi evitata se non in casi particolari.