从VB.net阵列插入SCLCE表

问题描述:

我很困惑,希望有人可以对我进行整理...我已经验证了一个文本文件,并且所有数据都被加载到一个数组中,准备添加到我的SQLCE表中.

这是我的代码,但是我遇到了一个问题,因为在"For Each"循环外无法识别变量"myTeam"……但是,如果我将For每个循环"都会失败,并显示错误此SqlCeParameterCollection已包含具有该名称的SqlCeParameter" ...我可能可以添加一个小计数器,并且第一次只处理这2行,但我确定有这样做是比更好"的更好方法!!!

I''m confused, hopefully somebody can sort me out ... I have validated a Text file and the data is all loaded into an Array, ready to be added to my SQLCE Table.

This is my code, but I am having a problem, in that the variable "myTeam" isn''t recognised as it outside the "For Each" loop ... however, if I move the "AddWithValue" lines inside the For "Each loop" it fails with the error "The SqlCeParameter with this name is already contained by this SqlCeParameterCollection" ... I could probably add a little counter and only process these 2 lines the first time through, but I''m sure there''s a better way of doing it than that, a *proper" way !!!

Using mySqlCmd As New SqlCeCommand("INSERT INTO Teams(TeamName, LeagueID) VALUES(@myValTeamName, @myValLeagueID)", mySqlConn)
    If mySqlConn.State = ConnectionState.Closed Then mySqlConn.Open()
    mySqlCmd.Parameters.AddWithValue("@myValTeamName", myTeam) << This Line
    mySqlCmd.Parameters.AddWithValue("@myValLeagueID", myLeagueID)
    For Each myTeam In myTeamList
        Using mySqlRdr As SqlCeDataReader = mySqlCmd.ExecuteReader()
            mySqlCmd.ExecuteNonQuery()
        End Using
    Next
End Using
mySqlConn.Close()

您可以在循环之前使用Parameters.Add而不是AddWithValue来添加参数,并在循环内部设置值.

但更重要的是,INSERT语句不使用阅读器...因此您可以把那行扔掉!
You can Add the parameters before the loop, using Parameters.Add instead of AddWithValue, and the set the value inside the loop.

But more significantly, INSERT statements do not use a Reader...so you can throw that line away!