【问题标题】:SQLite Argument out of rangeSQLite 参数超出范围
【发布时间】:2022-01-14 08:47:13
【问题描述】:

我正在尝试查询 SQL 数据库并收到以下错误:

引发了“System.ArgumentOutOfRangeException”类型的异常。 (参数“名称”)

请问我该如何解决这个问题?

Dim Connection As New SqliteConnection("Data Source = Database.db")
Dim SQLcommand As String = "SELECT * FROM Menu WHERE ItemID = 113"
Dim CMD As New SqliteCommand
 
Try
    CMD.Connection = Connection
    Connection.Open()
    CMD.CommandText = SQLcommand
    Dim reader As SqliteDataReader = CMD.ExecuteReader()
    While reader.Read()
        Order.Label3.Text = reader(reader("ItemID") & ", " & reader("Name") & ", " & reader("Price"))
    End While
    reader.Close()
    Connection.Close()
Catch e As Exception
    MessageBox.Show(e.Message)
End Try

【问题讨论】:

  • 不要使用打开的连接更新用户界面。

标签: sql database vb.net sqlite error-handling


【解决方案1】:

我认为您在此行中对reader 的调用次数过多:

Order.Label3.Text = reader(reader("ItemID") & ", " & reader("Name") & ", " & reader("Price"))

改成:

Order.Label3.Text = reader("ItemID") & ", " & reader("Name") & ", " & reader("Price")

【讨论】:

  • 谢谢。我发现这个解决方案是最基本且易于理解的。 :)
【解决方案2】:

将用户界面代码与数据库代码分开。连接、命令和DataReaders 需要调用它们的Dispose 方法来释放它们使用的非托管资源。 Using 块为我们做这件事。您可以将CommandTextConnection直接传递给命令的构造函数,而不是一一设置属性。我填写了DataTable 以传递给 UI 代码。 DataTable 不需要像DataReader 那样打开连接。我将连接字符串设置为表单级别的变量,因为我希望它可以在多个地方使用。

Private OPConStr As String = "Data Source = Database.db"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt As DataTable = Nothing
    Try
        dt = GetMenuData(113)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    If dt.Rows.Count > 0 Then
        Order.Label3.Text = String.Join(", ", {dt(0)("ItemID").ToString, dt(0)("Name").ToString, dt(0)("Price")})
    Else
        MessageBox.Show("No records returned")
    End If
End Sub

Private Function GetMenuData(ID As Integer) As DataTable
    Dim SQLcommand As String = "SELECT * FROM Menu WHERE ItemID = 113"
    Dim dt As New DataTable
    Using Connection As New SQLiteConnection(OPConStr),
            CMD As New SQLiteCommand(SQLcommand, Connection)
        CMD.Parameters.Add("@ID", DbType.Int32).Value = ID
        Connection.Open()
        Using reader = CMD.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
    Return dt
End Function

【讨论】:

  • 感谢您的回答。对于我目前的理解,我确实觉得这太复杂了,但感谢您抽出宝贵的时间。 :)
猜你喜欢
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多