我对.NET 编程相当陌生。我正在尝试检查数据库表中是否有设置,如果没有,请创建一些默认设置。问题是,当没有设置时,我需要使用数据读取器进行两次调用,并且它一直给我带来问题。
我最初只使用一个数据读取器,但做了两个尝试解决我的问题,没有用。
然后我尝试关闭数据读取器并收到错误,因为它返回了一个空引用。
如果我尝试关闭它,我会遇到问题,如果我不关闭它,下一个会给我一个错误,说这个连接上已经有一个打开的数据读取器需要关闭。谁能告诉我如何重构我的代码以使其正常工作(最好使用一个数据读取器)?
我还尝试将 reader.close() 放在另一组 try catch 中,虽然这使我能够捕获错误,但它仍然没有关闭 datareader,所以我不知所措。
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