我正在使用食谱库。我有一个包含3个列表框(lstIngredient,lstSelected,lstRecipe)和一个查找按钮的表单。 lstIngredient填充了存储在数据库中的成分名称。
当用户选择(双击)lstIngredient中的名称时,它将被列为lstSelected。之后,当用户点击查找按钮时,它将在数据库中找到食谱使用这些成分的内容。数据库中的表格如下所示:
id | recipe | ingredient
1 | spaghetti | tomato sause
2 | spaghetti | cheese
3 | spaghetti | hotdog
4 | burger | bread bun
5 | burger | burger patty
6 | burger | cheese
所以在这里,用户选择cheese
,bread bun
和hotdog
(注意:这些项目是逐个选择的),这些将在lstSelected中列出。单击“查找”按钮后,结果应为burger
和spaghetti
。如果您注意到,汉堡是列表中的第一项。例如,lstRecipe中的结果应取决于所选成分的出现次数。这就是我所做的:
Call Connect()
Dim dt As New DataTable
Dim cmd As New MySqlCommand
Try
lstRecipe.Items.Clear()
cmd.Connection = myConn
cmd.CommandText = "select recipe from cook_book where ingredient = @item"
cmd.Parameters.AddWithValue("item", lstSelected.Items)
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = cmd
myAdptr.Fill(dt)
lstRecipe.DisplayMember = "recipe"
For Each row As DataRow In dt.Rows
lstRecipe.Items.Add(row("recipe"))
Next
Dim builder As New StringBuilder()
builder.Append("select distinct recipe from cook_book where")
For y As Integer = 0 To lstSelected.Items.Count - 1
Dim parameterName As String = "@item" & y.ToString()
If y <> 0 Then
builder.Append("and ")
End If
builder.Append(parameterName)
builder.Append(" in (select ingredient from cook_book where recipe = i.recipe) ")
cmd.Parameters.AddWithValue(parameterName, lstSelected.Items(y))
Next
cmd.CommandText = builder.ToString()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
cmd = Nothing
myReader = Nothing
myConn.Close()
Call Disconnect()
代码在btnFind_Click事件下。我没有收到任何错误,但它没有按照应有的方式运行。它只找到用户选择的最后一种成分的最后一个配方。