使用数据集将值插入到2D数组VB.Net中

时间:2014-07-28 15:19:09

标签: vb.net dataset multidimensional-array

我正在尝试从数据库中的表中获取数据并将其放入数组中,然后将数据输入到数据库中的其他表中。我在使用数据集的2D数组时遇到了困难。

在下面的代码中,添加到Hname列的names(i,0)值非常有效。但是,当执行下一行时,名称(j,0)不起作用,但如果我将其交换到names(0,j),它会在数组中插入第一个值,即。位置0的值。我无法弄清楚为什么尝试在j处插入值不起作用。

Dim count As Integer = ds.Tables(0).Rows.Count
Dim names As String(,) = New String(count - 1, 4) {}
For i As Integer = 0 To count - 1
    For j As Integer = 0 To count - 1

        names(i, j) = ds.Tables(0).Rows(i)(0).ToString()

        Dim myconnectone As New SqlClient.SqlConnection
        myconnectone.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"
        Dim mycommandone As SqlClient.SqlCommand = New SqlClient.SqlCommand()
        mycommandone.Connection = myconnectone
        mycommandone.CommandText = "INSERT INTO Matches (HomeTeam,AwayTeam) VALUES (@Hname,@Aname)"
        myconnectone.Open()
        mycommandone.Parameters.Add("@Hname", SqlDbType.NVarChar).Value = names(i, 0)
        mycommandone.Parameters.Add("@Aname", SqlDbType.NVarChar).Value = names(0, j)
        mycommandone.ExecuteNonQuery()
    Next
Next

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

需要整理但尝试

Dim count As Integer = ds.Tables(0).Rows.Count
Dim ColCount As Integer = ds.Tables(0).Columns.Count
Dim names As String(,) = New String(count - 1, 4) {}
For i As Integer = 0 To count - 1
    For j As Integer = 0 To ColCount - 1

        names(i, j) = ds.Tables(0).Rows(i)(j).ToString()

    Next
    Dim myconnectone As New SqlClient.SqlConnection
    myconnectone.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"
    Dim mycommandone As SqlClient.SqlCommand = New SqlClient.SqlCommand()
    mycommandone.Connection = myconnectone
    mycommandone.CommandText = "INSERT INTO Matches (HomeTeam,AwayTeam) VALUES (@Hname,@Aname)"
    myconnectone.Open()
    mycommandone.Parameters.Add("@Hname", SqlDbType.NVarChar).Value = names(i, 0)
    mycommandone.Parameters.Add("@Aname", SqlDbType.NVarChar).Value = names(i, 1)
    mycommandone.ExecuteNonQuery()
Next