Datagridview - 正确执行更新/插入

时间:2016-11-23 09:13:35

标签: vb.net datagridview

我第一次这样做,我需要一些指导。我将Datagridviews设置为It的数据源。现在如何正确地更新或从其中将记录插入数据库?

我的问题:

  1. 目前我在Datagridviews下没有任何按钮(如添加/删除/更新 - 我是否毫无疑问需要它们或者是否可以在没有它们的情况下处理所有操作? - 我不使用TableAdapterManager!)

  2. MERGE语句 - 是否可以用于将某些表与Datagridview进行比较并在同一个表上执行更新或插入?

  3. 如果手动执行INSERT或UPDATE,首先是什么以及如何检查必须执行的操作?

  4. 我已经有了一个代码来执行这两个操作,但它不能正常工作,问题是我只有一个按钮用于在表单上保存数据 - 该按钮应该从2个Datagridviews +中插入或更新数据库中的数据表格上的数据绑定文本框。所以基本上有3个表可以在同一个表单上更新/插入 - Datagridviews显示相关数据,Databinded Texboxes显示主表记录。

    任何帮助都非常感激。

    编辑(这是我的完整代码 - 首先将数据加载到表单和Datagrid,然后是Btn_Save的代码):

    Imports System.Data
    Imports Oracle.DataAccess.Client ' ODP.NET Oracle managed provider
    Imports Oracle.DataAccess.Types
    
    Imports System.IO
    Imports System
    Imports System.Windows.Forms
    Imports System.ComponentModel
    
    Public Class Form2
    
        Private da, da1 As OracleDataAdapter
        Private cb, cb1 As OracleCommandBuilder
        Private ds, ds1 As DataSet
        Public OpenedForm1 As Form1 'required for obtaining record ID - this form opens when user double clicks on datagridview record
    
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
                BtnSave.Enabled = False 'for eliminating errors when using dataset Update (Oracle recommendation)
                Dim SQL1 As String = "SELECT * from TABLE1 WHERE ID_Table1=" &  OpenedForm1.DataGridView1.CurrentRow.Cells(0).Value.ToString
                Dim DGV1_SQL As String = "SELECT ID_TABLE2, ID_TABLE1, Name, Surname, WHERE ID_TABLE1=" & OpenedForm1.DataGridView1.CurrentRow.Cells(0).Value.ToString
                Dim DGV2_SQL As String = "SELECT TABLE3.SERIAL, TABLE3.MODEL," _
            & " TABLE3.TYPE FROM TABLE3 INNER JOIN (TABLE1 INNER JOIN TABLE1_TABLE3 ON TABLE1.ID_Table1=TABLE1_TABLE3.ID_Table1_FK) ON " _
            & "TABLE3.ID_Table3=TABLE1_TABLE3.ID_Table3_FK WHERE TABLE1_TABLE3.ID_TABLE1_FKK=" & Openedform1.DataGridView1.CurrentRow.Cells(0).Value.ToString
    
            Try
    
                Oracleconn()
    
    'Then I do all DB queries and display results on form
    'For SQL1 Databind all textboxes – this is a master record on form
    'For DGV2_SQL and DGV2_SQL fill datasets and set Datagrids to datasource
    'I'm also hiding all primary key fields and bounding datagrids to Binding sources to enable Binding navigators under them.
    
       End Sub
    
    
             Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
    
    'First I assign some variables for Oracle parameters, such as dealing with Null Date values
    
               Oracleconn() 'My connection to DB
    
            Using cmd As OracleCommand = New OracleCommand()
    
                cmd.Connection = Oracleconn()
                cmd.Parameters.Clear()
    
    'Adding a lot of paramters here for master record like this...
                cmd.Parameters.Add(New OracleParameter("ID", TxtID.Text))
    ))
    'Only Update for master record – Textboxes on form – works just fine
                cmd.CommandText = "UPDATE TABLE1" _
                   & " SET ID_TABLE1= : id .etc 
    
                If Not (TxtSerial.Text = "" Or TxtInventar.Text = "11111" Or TxtInventar.TextLength < 9) Then
    
                    cmd.ExecuteNonQuery()
                    cmd.Parameters.Clear()
    
    'Then checking 1st datagridview for data in It
                    For Each row As DataGridViewRow In DGV1.Rows
    
                        If row.Cells(1).Value <> Nothing Then
    
                            'Adding parameters again
    
    'Then my attempt for doing update or Insert with MERGE – doesn't work
    
                            cmd.CommandText = "MERGE INTO TABLE2 v" _
                                & "USING (SELECT * FROM TABLE2 WHERE ID_TABLE2='" & row.Cells(1).Value & "') u" _
                                & " ON u.ID_TABLE2" _
                                & " WHEN MATCHED THEN UPDATE SET all fields except ID's " _
                            '    & " WHEN NOT MATCHED BY v" _
                            '    & " THEN INSERT... all fields" _
                            '    & " VALUES.... from parameters"
    
    cmd.ExecuteNonQuery()
                            cmd.Parameters.Clear()
    
                            'This was used before, but ofcourse It only updates 
                            da.Update(ds.Tables(0))
    
                            BtnSave.Enabled = True
    
                        Else 
                            MsgBox("You cannot save without 1st field empty !")
                            Exit For
                        End If
    
                    Next
    
    'Then check for next Datagrid – this one is hard, It's a joined Table(entitity) from Table1 and Table3, with showing data from that joined Table too
                    For Each row As DataGridViewRow In DGV2.Rows
    
    'Adding parameters and just performing update – didn't start the Insert so far
    
                    MsgBox("Saved.", MsgBoxStyle.Information, "Editing records")
    
                    'Refresh Datagridview in Form1 - which is also opened
                    OpenedForm1.BtnSearch()
    
                Else 
                    MsgBox("1st field is required to be filled If you want to save.", MsgBoxStyle.Exclamation, "Editing records")
    
                End If
    
            End Using
    
            OracleClose() 'close my connection
    
        End Sub
    

2 个答案:

答案 0 :(得分:1)

你基本上需要先插入,然后更新,然后删除。您必须在子项之前插入父项,除非您的外键级联删除,否则在父项之前删除子项。对于更新,订单并不重要。 E.g。

Dim parentAdapter As SqlDataAdapter
Dim childAdapter As SqlDataAdapter

Dim data As DataSet

Dim parentTable As DataTable
Dim childTable As DataTable

'...

Dim parentInserts = parentTable.GetChanges(DataRowState.Added)
Dim parentUpdates = parentTable.GetChanges(DataRowState.Modified)
Dim parentDeletes = parentTable.GetChanges(DataRowState.Deleted)

Dim childInserts = childTable.GetChanges(DataRowState.Added)
Dim childUpdates = childTable.GetChanges(DataRowState.Modified)
Dim childDeletes = childTable.GetChanges(DataRowState.Deleted)

If parentInserts IsNot Nothing Then
    parentAdapter.Update(parentInserts)
End If

If childInserts IsNot Nothing Then
    childAdapter.Update(childInserts)
End If

If parentUpdates IsNot Nothing Then
    parentAdapter.Update(parentUpdates)
End If

If childUpdates IsNot Nothing Then
    childAdapter.Update(childUpdates)
End If

If childDeletes IsNot Nothing Then
    childAdapter.Update(childDeletes)
End If

If parentDeletes IsNot Nothing Then
    parentAdapter.Update(parentDeletes)
End If

data.AcceptChanges()

答案 1 :(得分:0)

让我尽可能以最好,最诚实的方式回答你,因为老实说,我之前就是这样做的。

我将根据我使用的Prog回答。郎。和数据库和幸运的是VB.Net是我的语言,MySQL是数据库。

我的答案:(按你的问题排序)

1.你问你是否需要它们?对我来说是的!因为我这样做了,想想一个带有DatagridView(填充数据)和3 Buttons(添加,更新,删除)的表单

  • Button: Add会将所有datagridview数据保存在表格中。您会看到一些链接或教程here
  • Button: Edit会根据您选择的内容here更新特定数据。我所做的是将它们转移到文本框并进行更新。
  • Button: Delete将根据您选择的行删除数据,按钮update的链接将成为您的指南,您只需编辑它Delete Query

2.10000%是的!看this,如果两者都相同,那么输出就是将颜色放在datagridview中。 (听起来很棒?喜欢它:D)

3. ping manualy对我来说很难,所以我的提示是为什么你不编辑你的datagridview然后Update Command Datagridview是可编辑的,但Pls提供至少1列,不会更新,因为它是基础您的where clause

所以你去了我说的所有我知道的东西,这将取决于你应该遵循什么,祝你好运和快乐编码

请记住:编码一个输出吨的执行方式没有错误