更新/编辑数据库

时间:2013-03-20 02:48:21

标签: sql-server vb.net visual-studio-2010 vb.net-2010

我知道这很简单,但我无法做到正确或找到任何搜索谷歌的答案。

我想更新/编辑数据。在数据库服务器中,单击我DataGridView上显示的数据。

下面是我的子编辑,代码不会自动将记录提取到文本框。

Private Sub btnEdit_Click(ByVal sender As System.Object, 
  ByVal e As System.EventArgs) Handles btnEdit.Click

  Dim transaction As SqlTransaction = Nothing

  With New SqlConnection(connectionString)
    Try
      Call .Open()
      transaction = .BeginTransaction()
      With .CreateCommand()
        .Transaction = transaction
        .CommandText = "UPDATE [tbl_info] SET [Name]=@Name WHERE [ID]=@ID;"
        With .Parameters
          .AddWithValue("ID", txtID.Text)
          .AddWithValue("Name", txtName.Text)
        End With
        Call .ExecuteNonQuery()
        Call transaction.Commit()
        Call MessageBox.Show("has been update successfully")
      End With
    Catch ex As Exception
      Call transaction.Rollback()
      Call MessageBox.Show(ex.Message, "Error")
    Finally
      Call .Close()
    End Try
  End With
  RefreshData()

  Call txtID.Clear()
  Call txtName.Clear()
End Sub

1 个答案:

答案 0 :(得分:0)

在ExecuteNonQuery行上,捕获受影响的行数。

Dim rc As Integer = .ExecuteNonQuery()

如果rc返回为零,我们可以告诉查询运行并且没有发现任何更新。