私は .NET プログラミングにかなり慣れていません。データベース テーブルに設定があるかどうかを確認しようとしています。ない場合は、デフォルト設定をいくつか作成します。問題は、設定がない場合、データリーダーで 2 つの呼び出しを行う必要があり、問題が発生し続けることです。
私はもともと1つのデータリーダーしか使用していませんでしたが、問題を解決するために2つ作成しましたが、うまくいきませんでした.
次に、データリーダーを閉じようとしましたが、null 参照が返されたためエラーが発生しました。
閉じようとすると問題が発生します。閉じないと、次のエラーで、この接続には閉じる必要がある開いているデータリーダーが既に存在するというエラーが表示されます。コードをリファクタリングしてこれを機能させる方法を誰か教えてもらえますか (できれば 1 つのデータリーダーで)。
また、reader.close() を try catch の別のセットに入れてみましたが、これによりエラーをキャッチできますが、まだデータリーダーを閉じないため、途方に暮れています。
Private Sub Get_Initial_Settings()
Dim reader1 As MySqlDataReader = Nothing, reader2 As MySqlDataReader = Nothing
Dim cmd As New MySqlCommand("SELECT depot, size, roc_family, wil_family, ast_family, met_family, ric_family, view FROM vb_dashboard.user_preferences WHERE " & GetUserName() & "", conn)
Dim hasSettings As Boolean
'Get Personal Settings or initiate them if necessary
Try
reader1 = cmd.ExecuteReader
hasSettings = True
MessageBox.Show("Your user settings show you have a selected depot of " & reader1(0).ToString)
Catch ex As Exception
'No settings exist, set some up
MessageBox.Show("You have no settings for this program yet")
hasSettings = False
Finally
reader1.Close()
End Try
'User has no preferences, Create some
'First, create a list of depots to select from and add it to a combobox
If (hasSettings = False) Then
Try
cmd.CommandText = "SELECT depot FROM vb_dashboard.depots ORDER BY depot"
reader2 = cmd.ExecuteReader
While (reader2.Read)
dlgSelectDepot.cbDepotSelect.Items.Add(reader2.GetString(0))
End While
'Now show the dialog box to initiate a depot setting
Me.Hide()
dlgSelectDepot.Show()
Me.Show()
If (dlgSelectDepot.DialogResult = Windows.Forms.DialogResult.Cancel) Then
Me.Close()
End If
cmd.CommandText = "INSERT INTO vb_database.user_preferences SET user='" & GetUserName.ToUpper & "', depot='Rochester'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("An error has occurred: " & ex.Message)
Finally
reader2.Close()
End Try
End If
End Sub