The safer way to do this is to actually call a stored procedure.
Separation of Concerns.
This is the line of code that I am talking about
Using command As New SqlCommand("SELECT TOP 1 ID FROM TblTable WHERE ID= '" & vVariable & "'", connection)
The code doesn't need to know how the database query is retrieving the information.
The stored procedure will run just as efficiently or faster, because the database will know about the procedure before it is run and have a "game plan" for it before it is called.
The variable should stay a variable all the way to the stored procedure.
you can remove the connection.Close()
and move the if statement outside of the Try Catch like this
Try Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQLLocal").ToString() Using connection = New SqlConnection(ConnectionString) Using command As New SqlCommand("SELECT TOP 1 ID FROM TblTable WHERE ID= '" & vVariable & "'", connection) connection.Open() Dim result = command.ExecuteScalar() End Using End Using Catch ex As Exception Return False End Try If result = "" Then Return False Else Return True End If
or you can get rid of the if else and the variable declaration altogether
Try Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQLLocal").ToString() Using connection = New SqlConnection(ConnectionString) connection.Open() Using command As New SqlCommand("SELECT TOP 1 ID FROM TblTable WHERE ID= '" & vVariable & "'", connection) Return Not String.IsNullOrEmpty(command.ExecuteScalar()) End Using End Using Catch ex As Exception Return False End Try
You will save a little bit when you nix the Variable creation
I somewhat agree with MrCochese.
If the code was returning a list of information with no input parameters needed, then I would say just use the string, but this code is asking for a very specific piece of information and needs a piece of input.
The code(application) gathers the input, sends it to the database. The database looks for the specified piece of information and returns it to the code(application). This shows a separation of concerns (there are two things happening here), input and query.
In the example of returning a simple set of information, only one things is happening, the return of information. There is no input or place for injection to occur.
so I stand by what I said about using a stored procedure, or better yet a user defined function because only one specific piece of information is being returned