Here's an example I wrote some time ago for querying SQL Server based on selections in a ListBox:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand
Dim query As New StringBuilder("SELECT * FROM MyTable")
Select Case Me.ListBox1.SelectedItems.Count
Case 1
query.Append(" WHERE MyColumn = @MyColumn")
command.Parameters.AddWithValue("@MyColumn", Me.ListBox1.SelectedItem)
Case Is > 1
query.Append(" WHERE MyColumn IN (")
Dim paramName As String
For index As Integer = 0 To Me.ListBox1.SelectedItems.Count - 1 Step 1
paramName = "@MyColumn" & index
If index > 0 Then
query.Append(", ")
End If
query.Append(paramName)
command.Parameters.AddWithValue(paramName, Me.ListBox1.SelectedItems(index))
Next index
query.Append(")")
End Select
command.CommandText = query.ToString()
command.Connection = connection
In that case, you can end up with three different types of queries:
- No items selected:
SELECT * FROM MyTable
- One item selected:
SELECT * FROM MyTable WHERE MyColumn = @MyColumn
- Multiple items selected:
SELECT * FROM MyTable WHERE MyColumn IN (@MyColumn0, @MyColumn1)
You can use the same code structure with the MySQL ADO.NET provider. You say that you have discrete variables but, however you identify which ones you need to include, I suggest that you place them in an array or collection and then you can use a loop in the same way I have in that code, looping over your array/collection instead of the SelectedItems of the ListBox.
ifstatement?ifthis then use 1 element,elseadd toarrayand use thearray.