I found this code to find a specific record in a table Sql.
Hi guys, I found this code and modified it to fit in my application. The code searches a specific record to display the result in a label. There is one text box to enter the word to search. Fill up the textboxes and one grid view. But I have found a word or face, I do not know what they are or do. And that is "SearchTerm" I don't know what the meaning is. Here is my code:
1) Dim command.Parameters.AddWithValue("@SearchTerm", "%" & searchTerm & "%")uery As String = "SELECT Company, Contacts, Telephone, Address, Email, AppoDate, AppoTime, Matters, Solutions
2) command.Parameters.AddWithValue("@SearchTerm", "%" & searchTerm & "%").
I appreciate your help and your time in advance. Thank you, wonderful Community guys.
Re: I found this code to find a specific record in a table Sql.
What you are doing is defining parameters to be used in a parameterized query. Here is the relevant documentation: https://learn.microsoft.com/en-us/do...ter-data-types
Specifically, you're using the AddWithValue method which will work, although I personally prefer the Add method and set the Value property -or- defining a new Parameter object so that I can be more explicit in the type of parameter I'm using.
In this case, you're telling your command object that you want to use a parameter named @SearchTerm in your SQL query and you want its value to be the variable searchTerm wrapped in percentage signs which indicates a LIKE search with wildcards before and after the value.
Take this for example:
Code:
Dim searchTerm As String = "Some Value"
Dim commandQuery As String = "SELECT MyTable.* FROM MyTable WHERE MyTable.MyField LIKE @SearchTerm;"
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(commandQuery, connection)
Dim searchTermParameter As New SqlParameter()
parameter.ParameterName = "@SearchTerm"
parameter.SqlDbType = SqlDbType.VarChar
parameter.Direction = ParameterDirection.Input
parameter.Value = $"%{searchTerm}%"
command.Parameters.Add(parameter)
' or in your example: command.Parameters.AddWithValue("@SearchTerm", $"%{searchTerm}%")
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
' do something with the results
End Using
connection.Close()
End Using
End Using
This code queries the SQL table named MyTable where the MyTable.MyField column contains the value: Some Value
Using parameters in your SQL is very important because it allows for better code reusability and more importantly guards against SQL injection attacks (helpful content).