私はレシピライブラリに取り組んでいます。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
したがって、ここでは user selected とcheese
しbread bun
ますhotdog
(注: これらのアイテムは 1 つずつ選択されます)、これらは 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 イベントの下にあります。エラーは発生しませんが、正常に機能していません。ユーザーが選択した最後の材料の最後のレシピのみが検索されます。