【发布时间】:2015-09-11 11:10:31
【问题描述】:
大家好,我在将调查数据插入数据库时遇到了一些问题,该数据库包含一堆具有外键+主键关系的复合表。您可以从上面的 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”中。
-
子表中的外键,对应的主键必须预先存在于父表中。