【问题标题】:How do I input multiple values into database tables with composite tables?如何将多个值输入到具有复合表的数据库表中?
【发布时间】:2015-09-11 11:10:31
【问题描述】:

Database ER Diagram

大家好,我在将调查数据插入数据库时​​遇到了一些问题,该数据库包含一堆具有外键+主键关系的复合表。您可以从上面的 ERDiagram 中看到关系是什么样的(我知道我搞砸了 M:M 关系,但如果您可以忽略,您可以从 PK 和 FK 中看到关系)。

这是我来自 WebFormApplication 的 C# 代码:

int GID, AID, SID, ISP =0;
        string homeSub, homePC, workSub, workPC, email ="";
        List<int> CarMakes = new List<int>();
        List<int> Banks = new List<int>();
        List<int> addService = new List<int>();
        List<int> addISP = new List<int>();

        GID = rblGender.SelectedIndex+1;
        AID = ddlAge.SelectedIndex+1;
        SID = ddlState.SelectedIndex + 1;
        ISP = ddlISP.SelectedIndex + 1;

        homeSub = tbxHomeSuburb.Text;
        homePC = tbxHomePostCode.Text;
        workSub = tbxWorkSuburb.Text;
        workPC = tbxWorkPostcode.Text;
        email = tbxEmailAdd.Text;

        //Validation stuff here:

        //if empty blah blah

        SqlConnection myConnection;
        SqlCommand queryCommand;
//This string is correct, I have used it plenty of times to Databind data to the form            
String myConnectionString = "Login Creditials are hidden";

        myConnection = new SqlConnection();
        myConnection.ConnectionString = myConnectionString;
        //I need one command to insert all survey data into their respective tables with the RID as a FK to connect all the data back to that respondent
        String sqlCommand = "INSERT INTO RESPONDENT (email, home_postcode, home_suburb, work_postcode, work_suburb) VALUES ('"+email+"','"+homePC+"','"+homeSub+"','"+workPC+"','"+workSub+"');";

        queryCommand = new SqlCommand(sqlCommand, myConnection);

        // Perform connect
        myConnection.Open();
        SqlDataReader dataReader = queryCommand.ExecuteReader();

如果该信息完全有用,则会在按钮单击事件上触发。如果有人可以帮助解决这个问题,请提前感谢您!

【问题讨论】:

  • 您遇到的错误是什么?
  • 没有特别的错误。我只是想知道如何将我从调查中收集的所有数据一次性插入到单独的表格中。
  • 每个父子关系从父表开始,一次插入一张表。
  • 好的,现在我似乎收到了一个错误:System.Data.dll 中发生了“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理其他信息:INSERT语句与 FOREIGN KEY 约束“FK_Gender_Respond”冲突。冲突发生在数据库“DB_9AB8B7_DDA5041”、表“dbo.GENDER”、列“GID”中。
  • 子表中的外键,对应的主键必须预先存在于父表中。

标签: c# mysql sql database


【解决方案1】:
  1. 您插入到respond 表中。
  2. 获取创建的自动数字RIDHere Is How
  3. 使用RID 插入到另一个表中,执行多个插入操作。

【讨论】:

  • 啊,自动数字 RID 是我卡住的地方。那么在 RESPONDENT 表上使用 SCOPE_IDENTITY 会返回我之前自动递增的 RID?
  • 是的,但是您可以将INSERTSELECT 合二为一,例如显示SqlCommand
猜你喜欢
  • 2023-03-21
  • 2016-10-03
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多