使用不同的值更新所有行

时间:2016-06-02 16:10:10

标签: vb.net ms-access

我有一个喜欢vb.net应用程序的Access数据库表 我需要为每一行更新具有不同值的所有行!
更新前的表:

 Column1 | Column2 | Column3  
   abc1  |   123   |
   abc2  |   345   

**Table After Update:**  
Column1 | Column2 | Column3   
 abc1   |   123   | x  
 abc2   |   345   | y  

我正在使用此代码:

For i = 0 To dgv.Rows.Count - 1
        Dim expDate As Date = dgv.Rows(i).Cells(6).Value
        dgv.Rows(i).Cells(8).Value = DateDiff(DateInterval.Day, Today.Date, expDate)
        Dim conn1 As OleDbConnection = New OleDbConnection(constroledb)
        Dim cmd1 As New OleDbCommand
        conn1.Open()
        cmd1.Connection = conn1
        cmd1.CommandText = "update tblvac set fld1 = '" & dgv.Rows(i).Cells(8).Value & "'  where vid = '" & dgv.Rows(i).Cells(0).Value & "' "
        cmd1.ExecuteNonQuery()
        cmd1.Dispose()
        conn1.Close()
Next

任何人都可以帮忙怎么做?

1 个答案:

答案 0 :(得分:0)

我同意Plutonix,你可以保持打开但没有循环的连接。我相信你可能在ID没有正确更新的sql插入的where子句中遇到问题。试试这个:

Using conn1 As New OleDb.OleDbConnection(constroledb)
        conn1.Open()
        For i As Integer = 0 To dgv.Rows.Count - 1
            Dim expDate As Date = dgv.Rows(i)(6)
            dgv.Rows(i)(8) = DateDiff(DateInterval.Day, Today.Date, expDate)
            Dim cmd1 As New OleDb.OleDbCommand
            cmd1.Connection = conn1
            cmd1.CommandType = CommandType.Text
            cmd1.CommandText = "UPDATE tblvac SET fld1 = @fld1 WHERE vid = @vid"
            cmd1.Parameters.AddWithValue("@fld1", dgv.Rows(i)(8))
            cmd1.Parameters.AddWithValue("@vid", dgv.Rows(i)(0))
            cmd1.ExecuteNonQuery()
            cmd1.Dispose()
        Next
    End Using

我将连接移动到一个使用,因此它将在循环完成时关闭,然后参数化查询,以便它允许字符串中的特殊字符实例而不抛出sql