SQLite 参数超出范围

SQLite Argument out of range

我正在尝试查询 SQL 数据库,但出现以下错误:

Exception of type 'System.ArgumentOutOfRangeException was thrown. (Parameter 'name')

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

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

我认为您在这一行中对 reader 的调用过多:

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

改为:

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

将用户界面代码与数据库代码分开。连接、命令和 DataReader 需要调用它们的 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