【发布时间】:2020-06-04 07:28:40
【问题描述】:
我有一个带有 datagridview 的表单,它在使用条形码扫描仪扫描后显示 db 表中的列,然后显示的数据应该插入到另一个表中,其中包含来自表单的附加信息,如组合框文本和标签文本,但我一直报错。这是我使用的代码,它适用于其他表单,但不适用于这个,我无法找出问题所在。
Sub SewingReport()
Try
Dim sdate As String = Now.ToString("yyyy-MM-dd")
If MsgBox("Are you sure you want to save this record to Sewing Report?", vbYesNo + vbQuestion) = vbYes Then
cn.Open()
cm = Nothing
cm = New MySqlCommand("insert into tblsewingreport (tsnumber, bundle#, itemcode, operation, color, size, quantity, price, amount, sdate, employee) values(@tsnumber, @bundle#, @itemcode, @operation, @color, @size, @quantity, @price, @amount, @sdate, @employee)", cn)
For i = 0 To dgvRecord.Rows.Count - 1
cm.Parameters.Clear()
cn.Close()
cn.Open()
cm.Parameters.AddWithValue("@tsnumber", lblInvoice.Text)
cm.Parameters.AddWithValue("@bundle#", dgvRecord.Rows(i).Cells("Column6").Value.ToString)
cm.Parameters.AddWithValue("@itemcode", dgvRecord.Rows(i).Cells("Column4").Value.ToString)
cm.Parameters.AddWithValue("@operation", dgvRecord.Rows(i).Cells("Column5").Value.ToString)
cm.Parameters.AddWithValue("@color", dgvRecord.Rows(i).Cells("Column7").Value.ToString)
cm.Parameters.AddWithValue("@size", dgvRecord.Rows(i).Cells("Column8").Value.ToString)
cm.Parameters.AddWithValue("@quantity", CDec(dgvRecord.Rows(i).Cells("Column9").Value.ToString))
cm.Parameters.AddWithValue("@price", CDec(dgvRecord.Rows(i).Cells("Column10").Value.ToString))
cm.Parameters.AddWithValue("@amount", CDec(dgvRecord.Rows(i).Cells("Column11").Value.ToString))
cm.Parameters.AddWithValue("@sdate", sdate)
cm.Parameters.AddWithValue("@employee", ComboBox1.Text)
cm.ExecuteNonQuery()
cn.Close()
Next
MinusStockQty()
MsgBox("Record has been successfully saved to Sewing Report.", vbInformation)
lblInvoice.Text = GetInvoiceNo()
txtSearch.Clear()
txtSearch.Focus()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.ToString)
End Try
End Sub
这是exception 消息,错误在 ExecuteNonQuery 行上引发,并且我所有的数据网格列名称都是正确的。这是datagridview,这是我正在尝试插入的database table。
【问题讨论】:
-
由于各种原因,您所做的事情在不同程度上是错误的。首先,不要在循环的每次迭代中打开和关闭连接。打开连接一次,通过该连接执行与数据库的所有交互,然后关闭它。
-
其次,您根本不应该真正使用
AddWithValue,但在这种情况下肯定不会。而不是ClearParameters集合和Add每次迭代的新参数,你应该只Add参数一次,然后在每次迭代中设置每个参数的Value。 -
最后,您根本不应该使用循环。您应该做的是使用适当的架构创建一个
DataTable,并将其绑定到您的网格。您可以自己将列添加到DataTable,也可以在数据适配器上调用FillSchema。当您准备好保存时,您可以在数据适配器上调用Update以一次性保存整个DataTable。您可以使用相同的数据适配器调用FillSchema和Update,如果需要,您可以使用命令生成器来生成InsertCommand以及所有参数。 -
实际上,我发现您的代码存在另一个问题。你为什么要使用
Date并将其转换为String,然后将其保存到数据库中?请告诉我您没有将日期存储为文本。您应该将日期存储为日期,这意味着将Date保存到数据库中。这意味着,至少,使用这个:cm.Parameters.AddWithValue("@sdate", Date.Today). -
感谢 jm 的所有观察!我仍在努力学习东西,这很有帮助。我现在删除了代码中的另外 2 个关闭和打开连接。我正在清除参数并使用 addwithvalue,因为我收到一条错误消息,提示“算术运算导致溢出”,该错误是从参数行抛出的。
标签: mysql vb.net exception datagridview parameters