VBNET如何在两个表的不同行中插入多个值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VBNET如何在两个表的不同行中插入多个值相关的知识,希望对你有一定的参考价值。
编码时如何将两个表链接在一起并将多个值插入不同的行?就像员工购买了3件商品一样,它会出现在另一张桌子上,并且每件商品每行而不是一列。
我不知道如何进行处理,如果您能提供帮助,将不胜感激。
Items:
[X] Bread
[] Milk
[X] Tools
[] Books
例如:
**Table 1: Employee**
EmpID (Primary key)
Name
TotalPurchased
**Table 2: EmployeeDetails**
ED_ID (Primary key)
EmpID (Foreign key)
Items
答案
在第一个Sub中要注意的重要事项是Select Scope_Identity()
,它返回连接上最后插入的标识。
第二个Sub添加@ID
参数并在循环外设置其值。 (每个项目都相同)@Item
参数被添加到循环外部的参数集合中,并且其值在循环内部设置。该连接在循环外部打开一次。该命令在循环的每次迭代中执行。
Private Sub InsertEmployee(Name As String, Purchase As Decimal, Items As List(Of String))
'This code assumes that EmpID is an identity field (auto-increment)
'and therefore not included in the Insert
Dim strSql = "Insert Into Employee (Name, TotalPurchased) Values (@Name, @Purchase); Select Scope_Identity();"
Dim EmployeeID As Integer
Using cn As New SqlConnection("Your connection String"),
cmd As New SqlCommand(strSql, cn)
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100).Value = Name
cmd.Parameters.Add("@Puchase", SqlDbType.Decimal).Value = Purchase
cn.Open()
EmployeeID = CInt(cmd.ExecuteScalar)
End Using
InsertItems(EmployeeID, Items)
End Sub
Private Sub InsertItems(Id As Integer, PurchaseItems As List(Of String))
'This code assumes that ED_ID is an identity field (auto-increment)
'and therefore not included in the Insert
Dim strSql = "Insert Into EmployeeDetails (EmpID, Items) Values (@ID, @Item);"
Using cn As New SqlConnection("Your connection String"),
cmd As New SqlCommand(strSql, cn)
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Id
cmd.Parameters.Add("@Item", SqlDbType.NVarChar, 100)
cn.Open()
For Each i In PurchaseItems
cmd.Parameters("@Item").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
如何使用代码的示例。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CheckBoxes = {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
Dim lst As New List(Of String)
For Each c In CheckBoxes
If c.Checked Then
lst.Add(c.Text)
End If
Next
Dim PurchaseAmount As Decimal
If Decimal.TryParse(TextBox2.Text, PurchaseAmount) Then
InsertEmployee(TextBox1.Text, PurchaseAmount, lst)
Else
MessageBox.Show("Please enter a valid amount for Purchase")
End If
End Sub
以上是关于VBNET如何在两个表的不同行中插入多个值的主要内容,如果未能解决你的问题,请参考以下文章