插入多对多数据库?

时间:2014-03-20 07:03:16

标签: c# sql many-to-many relational-database

伙计们我正在尝试学习多对多关系数据库,但我在" link / junction"中插入数据时遇到了麻烦。表。 这就是我的数据库的样子: enter image description here

现在我的应用程序是C#中的Windows桌面应用程序,我有一个简单的表单,其中我有5个文本框和&一个按钮,这就是它的样子:

enter image description here

注意:图像2 - 红色表示带有.Text的文本框名称,蓝色表示我将要输入的数据类型。工程师ID 1,2和3已存在于表tblEngineer中。

现在按下添加,我想输入值Date&表Phone Number中的tblTicketDetail和表EngineerID 1中的EngineerID 2EngineerID 3tblTicket_Engineer的值。表tblEngineer已经有一些行。

现在如果我只在tblTicket_Engineer中输入一个EngineerID,我会在"添加"的点击事件中执行此操作。按钮:

        string statement = "INSERT INTO tblTicketDetail(IssueDate,Number) VALUES(@text1,@text2);SELECT SCOPE_IDENTITY()";
        using (SqlCommand command = new SqlCommand(statement))
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString()))
        {

                command.Parameters.AddWithValue("@text1", textBox1.Text);
                command.Parameters.AddWithValue("@text2", textBox2.Text);
                connection.Open();
                command.Connection = connection;
                ID = command.ExecuteScalar().ToString();
                connection.Close();
        }

        string statement1 = "INSERT INTO tblTicket_Engineer(ID,EID) VALUES(@text1,@text3)";
        using (SqlCommand command1 = new SqlCommand(statement1))
        using (SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString()))
        {

            command1.Parameters.AddWithValue("@text1", ID);
            command1.Parameters.AddWithValue("@text3", textBox3.Text);
            connection1.Open();
            command1.Connection = connection1;
            command1.ExecuteNonQuery();
            connection1.Close();
        }

查看表tblTicket_Engineer中的外键,并告诉我外键是否正确。

enter image description here

如何在表tblTicket_Engineer中一次输入3行? 当我按下添加按钮时,我想在tblTicket_Engineer中发生这种情况(对于此图像,手动输入值)

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL。尝试这样的事情:

        string statement1 = @"INSERT INTO tblTicket_Engineer(TicketID,EngineerID) 
                        SELECT @ID,@EID1 UNION ALL
                        SELECT @ID,@EID2 UNION ALL
                        SELECT @ID,@EID3";
        using (SqlCommand command1 = new SqlCommand(statement1))
        using (SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString()))
        {

            command1.Parameters.AddWithValue("@ID", PID);
            command1.Parameters.AddWithValue("@EID1", comboBox1.SelectedValue);
            command1.Parameters.AddWithValue("@EID2", comboBox2.SelectedValue);
            command1.Parameters.AddWithValue("@EID3", comboBox3.SelectedValue);
            connection1.Open();
            command1.Connection = connection1;
            command1.ExecuteNonQuery();
            connection1.Close();