gpt4 book ai didi

Resave the DataGridView contect into database(将DataGridView内容重新保存到数据库中)

转载 作者:bug小助手 更新时间:2023-10-27 21:08:24 31 4
gpt4 key购买 nike



I am saving DataGridView data into SQL database which is running ok. I want to resave the grid but first want to delete the existing rows of same number PO from database. For this i used Delete command of same PO Number before inserting to database.

我正在将DataGridView数据保存到运行正常的SQL数据库中。我想重新保存网格,但首先要从数据库中删除相同数量的现有行PO。为此,我使用了删除命令相同的采购订单号插入到数据库之前。


Now if by any chance there is an error in Insert procedure, it delete the existing rows and shows error.

现在,如果INSERT过程中出现错误,它将删除现有行并显示错误。


I want if there is an error, the delete procedure can not be run. how to check this?

我希望如果出现错误,删除程序将无法运行。怎么查这个?


Private Sub SaveData()
Try
DeleteData()

Dim i As Integer
Dim answer As Integer
answer = MsgBox("Are you sure to save?", vbQuestion + vbYesNo + vbDefaultButton1, "Save Record")
If answer = vbYes Then
ConnecDatabase()
Sql = "Operation_InsertPO"
For i = 0 To DGV_PO.RowCount - 1
cmd = New SqlCommand
With cmd
.Connection = Conn
.Parameters.Clear()
.CommandType = CommandType.StoredProcedure
.CommandText = Sql
.Parameters.AddWithValue("@PONo", text_ponumber.Text)
.Parameters.AddWithValue("@ProductCode", DGV_PO.Rows(i).Cells(2).Value)
.Parameters.AddWithValue("@ProductName", DGV_PO.Rows(i).Cells(3).Value)
.Parameters.AddWithValue("@Units", DGV_PO.Rows(i).Cells(4).Value)
.Parameters.AddWithValue("@Qty", DGV_PO.Rows(i).Cells(5).Value)
.Parameters.AddWithValue("@Rate", DGV_PO.Rows(i).Cells(6).Value)
.Parameters.AddWithValue("@Amt", DGV_PO.Rows(i).Cells(7).Value)
.Parameters.AddWithValue("@User", GlobalVariables.UserName)
.ExecuteNonQuery()
End With
Next
cmd.Dispose()
Conn.Close()
MsgBox("Saved Successfuly", vbInformation)
End If
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
Finally
If Conn.State = ConnectionState.Open Then
Conn.Close()
End If
End Try
End Sub

Private Sub DeleteData()
Try
ConnecDatabase()
Sql = "Operation_DeletePO"
cmd = New SqlCommand
With cmd
.Connection = Conn
.Parameters.Clear()
.CommandType = CommandType.StoredProcedure
.CommandText = Sql
.Parameters.AddWithValue("@pono", text_ponumber.Text)
.ExecuteNonQuery()
End With
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
Finally
If Conn.State = ConnectionState.Open Then
Conn.Close()
End If
End Try
End Sub

更多回答

Not directly related to your question but I suggest one avoid AddWithValue.

与您的问题没有直接关系,但我建议您避免使用AddWithValue。

Run your delete command after inserting? Or put it all in the same SP?

是否在插入后运行删除命令?或者将其全部放在同一个SP中?

Use a transaction to wrap both the delete and insert operations. The whole point of transactions is to ensure that either all operations complete or none do, i.e. exactly what you want to happen.

使用事务来包装删除和插入操作。事务的全部要点是确保所有操作要么完成,要么不完成,即您希望发生的事情。

优秀答案推荐
更多回答

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com