如何在联结表中插入值? [英] How to insert values in a junction table?

查看:89
本文介绍了如何在联结表中插入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在名为'insert_Students_Scholarships_junction'的联结表中输入值,该表有两列/键'student_pk'和'scholarship_id'。此联结表以多对多关系连接两个表。这些表分别是学生和奖学金,主键分别为'student_pk'和'scholarship_id'。

我已经使用'scholarship_id'检索了另一个子。这个子没有问题。







I am trying to enter values in a junction table called 'insert_Students_Scholarships_junction' that has two columns/keys 'student_pk' and, 'scholarship_id'. This junction table connects two tables in a many-to-many relationship.The tables are Students and Scholarships with the primary keys 'student_pk' and 'scholarship_id' respectively.
I have already retrieved 'scholarship_id' using another sub. there is no problem with that sub.



Public Sub insert_Students_Scholarships_junction()
       DataGridView1.Refresh()
       con.Open()
       Dim da As New SqlDataAdapter(" SELECT student_pk FROM Students WHERE scholarship_id= '" & scholarship_id & "'", con)
       Dim dt As New DataTable
       dt.Clear()
       da.Fill(dt)
       DataGridView1.DataSource = dt

       For Each Dr As DataRow In dt.Rows
           Dim cmd1 As New SqlCommand
           cmd1.Connection = con
           cmd1.CommandText = "INSERT INTO Students_Scholarships_junction(student_pk,scholarship_id) VALUES(@pk, @id)"
           cmd1.CommandType = CommandType.Text
           cmd1.Parameters.AddWithValue("pk", dt.Rows.Item(0))
           cmd1.Parameters.AddWithValue("id", scholarship_id)
           cmd1.ExecuteNonQuery()
           MsgBox("successful")

       Next
       con.Close()
   End Sub





我收到以下错误:'从对象类型System.Data.DataRow到已知的托管提供者本机类型没有映射。'与此行'cmd1.ExecuteNonQuery()'相关联。 />


1)如何纠正错误?我知道,对于每次迭代,我需要访问行中的第一项。但它是如何做到的?



I get the following error: 'No mapping exists from object type System.Data.DataRow to a known managed provider native type.' assoicated with this line' cmd1.ExecuteNonQuery()'

1)How do i rectify the error? I know that for each iteration i need to access the first item in the row. but how do it do it?

推荐答案

dt.Rows.Item(0)返回一个对象。简单地把它投入到你的PK中就完成了。



如果这有帮助请花时间接受解决方案。谢谢。
dt.Rows.Item(0) returns an object. Simply cast it into whatever your pk is and you're done.

If this helps please take time to accept the solution. Thank you.


检查这个错误:从对象类型System.Data.DataRowView到已知的托管提供者本机类型不存在映射 [ ^ ]


dr.item(0)

,而不是像之前那样。


这篇关于如何在联结表中插入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆