0

我在运行以下命令时收到错误“字典中不存在给定的键”,有什么办法解决这个问题吗?谢谢

            Dim con As New SqlConnection
            Dim cmd As New SqlCommand
            con.ConnectionString = "Data Source=USER\SQLEXPRESS;Initial Catalog=DBName;Integrated Security=SSPI"
            con.Open()
            cmd.Connection = con
            Try
                Dim InsertCommand As New SqlCommand

                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name
                cmd.Parameters.Add("@rowdata.Item(0)", SqlDbType.VarChar).Value = rowData.Item(0)
                cmd.Parameters.Add("@rowdata.Item(1)", SqlDbType.VarChar).Value = rowData.Item(1)
                cmd.Parameters.Add("@rowdata.Item(2)", SqlDbType.VarChar).Value = rowData.Item(2)
                cmd.Parameters.Add("@rowdata.Item(3)", SqlDbType.VarChar).Value = rowData.Item(3)
                cmd.Parameters.Add("@rowdata.Item(4)", SqlDbType.VarChar).Value = rowData.Item(4)
                cmd.Parameters.Add("@rowdata.Item(5)", SqlDbType.VarChar).Value = rowData.Item(5)

            Catch ex1 As Exception
                MessageBox.Show("Error!" & ex1.Message)

                cmd.CommandText = "INSERT INTO allData (Name, Num1, Num2, Num3, Num4, Num5, Num6) VALUES (@Name,rowData.Item(0),rowData.Item(1),rowData.Item(2),rowData.Item(3),rowData.Item(4),rowData.Item(5))"
                cmd.ExecuteNonQuery()

            Finally
                con.Close()
            End Try
4

1 回答 1

3

Change your code to

Try
    Dim InsertCommand As New SqlCommand
    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name
    cmd.Parameters.Add("@num1", SqlDbType.VarChar).Value = rowData.Item(0)
    cmd.Parameters.Add("@num2", SqlDbType.VarChar).Value = rowData.Item(1)
    cmd.Parameters.Add("@num3", SqlDbType.VarChar).Value = rowData.Item(2)
    cmd.Parameters.Add("@num4", SqlDbType.VarChar).Value = rowData.Item(3)
    cmd.Parameters.Add("@num5", SqlDbType.VarChar).Value = rowData.Item(4)
    cmd.Parameters.Add("@num6", SqlDbType.VarChar).Value = rowData.Item(5)
    cmd.CommandText = "INSERT INTO allData (Name, Num1, Num2, Num3, Num4, Num5, Num6) " + 
                      "VALUES (@Name,@num1,@num2,@num3,@num4,@num5,@num6)"
    cmd.ExecuteNonQuery()
Catch ex1 As Exception
    MessageBox.Show("Error!" & ex1.Message)
Finally
    con.Close()
End Try

As you have written the code above, the execution of the command is inside the catch clause and this means that it is executed only if there is an exception in the preparation of the Parameters.
However this could only be a typo, more problematic are the parameter names.
I suggest you to simplify the placeholders names using a simple pattern.

于 2013-06-15T19:52:35.987 回答