VB.NET 数据集更新
Posted
技术标签:
【中文标题】VB.NET 数据集更新【英文标题】:VB.NET DataSet Update 【发布时间】:2009-11-08 06:45:55 【问题描述】:为什么我的代码集没有在 DataSet 中更新?然后它进入错误。请任何人检查此代码并指出我失踪的地方。提前致谢!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
Dim cmdSelectCommand As SqlCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
cmdSelectCommand.CommandTimeout = 30
dadPurchaseInfo.SelectCommand = cmdSelectCommand
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID").ToString()) = 2 Then
dRow.Item("StockCode") = "Re-Fashion[G]"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : ")
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
End Try
End Sub
【问题讨论】:
可以贴一下抛出的异常信息吗?它是从哪一行代码抛出的? 嗨。 ○。 ķ。 w,这是我收到的异常消息-------- InvalidOperationException 被捕获 不支持不返回任何键列的SelectCommand 为UpdateCommand 生成动态SQL信息。 ------------ @RedsDevils:你的“stock”表有主键列吗? 不!我使用 StockID 作为主键,但我没有在 Table Structre 中定义。 @RedsDevils:建议您将该列设置为主键,但这不是重点。我只是猜测查询构造函数无法为没有标识符的表生成更新语句。 【参考方案1】:循环中的条件是否被执行(设置断点!)?错误在哪里抛出? 什么错误?
另外,为什么它使用ToString
?这似乎是多余的。
If CInt(dRow.Item("StockID")) = 2 Then
应该够了。
最后,您正在执行冗余清理:
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
Dispose
暗示 Close
- 无需执行这两个操作:
Close
和Dispose
在功能上是等效的。
[Source: MSDN]
【讨论】:
感谢康纳德·鲁道夫!我是根据您对我的程序的错误更正得到它的! :) 非常感谢。我花了一整天的时间来解决!非常感谢!【参考方案2】:你的dataAdapter有更新命令吗?
(看起来它没有 - 所以它不知道如何处理更新......)
这是一个更新命令示例:(对于具有 3 列的员工表 - 如下所列:
UPDATE [Employee]
SET [name] = @name
, [manager] = @manager
WHERE (([id] = @Original_id) AND
((@IsNull_name = 1 AND [name] IS NULL) OR
([name] = @Original_name)) AND
((@IsNull_manager = 1 AND [manager] IS NULL) OR
([manager] = @Original_manager)));
SELECT id
, name
, manager
FROM Employee
WHERE (id = @id)
你可以看到它是一个通用的更新,可以处理任何领域的变化。
【讨论】:
这部分怎么样? For Each dRow In dsPurchaseInfo.Tables("Stock").Rows If CInt(dRow.Item("StockID").ToString()) = 2 Then dRow.Item("StockCode") = "Re-Fashion[G]" End If Next 说要更新dataAdapter,不是吗? 你给了适配器一个选择命令(检查你的代码)你需要给它一个更新命令。您的代码会更改数据 - 但适配器需要知道要运行什么命令来更新它。您可以使用 Visual Studio 向导生成更新命令,也可以自己编写。 Dim cmdUpdateCommand As SqlCommand = New SqlCommand("UPDATE Stock SET StockCode='Re-Fashion(H)' WHERE StockID=2", conxMain) cmdUpdateCommand.CommandTimeout = 30 dadPurchaseInfo.UpdateCommand = cmdUpdateCommand Dim cbUpdate As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo) dadPurchaseInfo.Update(dsPurchaseInfo, "Stock") ------------- 我像上面一样写并运行,但它不起作用。 你能告诉我在 Visual Studio 中创建更新查询后调用的代码 sn-p 吗?【参考方案3】:我从 Konard Rudolph 对我的程序的纠错中得到它!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
dadPurchaseInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID")) = 2 Then
dRow.Item("StockCode") = "Re-Fashion(H)"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : " & vbCrLf & ex.Message)
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Dispose()
End If
End Try
End Sub
上面的代码集可以使用 DataSet 进行更新!感谢 *** 社区和谁回答了我的问题。
这里是参考:
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual Basic .NET How to update a database from a DataSet object by using Visual Basic .NETp.s:就像 o.k.w 说的:表必须有主键。谢谢你好!
【讨论】:
【参考方案4】:--MENU--
Dim login As New LoginClass
login.ShowDialog()
--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
Get
Return conec
End Get
End Property
Public Sub Conectar()
Try
conec = New SqlConnection(stringCon)
If conec.State <> ConnectionState.Open Then
conec.Open()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt
--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()
--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"
--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
Dim FLstArticulos As New FLstArticulos
FLstArticulos.ShowDialog()
DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If
--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
Dim precio As New Double
Dim cantidad As New Double
precio = CDbl(grdRow.Cells(2).Value)
cantidad = CDbl(grdRow.Cells(3).Value)
DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
PLCargaTotales()
End If
Sub PLCargaTotales()
Dim subTotal As Double
Dim iva As Double
For Each grd As DataGridViewRow In DataGridProductos.Rows
If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
subTotal = subTotal + CDbl(grd.Cells(4).Value)
End If
Next grd
txtSubtotal.Text = subTotal.ToString
iva = Decimal.Round(subTotal`enter code here` * 0.12)
txtIva.Text = iva.ToString
txtTotalPagar.Text = (subTotal + iva).ToString
End Sub
【讨论】:
我不确定那些--XYZ--
标头应该是 cmets、#region
s 还是只是常规的帖子文本,但因为它们无法编译,您应该修复那个。
欢迎来到 ***。虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。以上是关于VB.NET 数据集更新的主要内容,如果未能解决你的问题,请参考以下文章