C# 使用C将外键插入带有SQL查询的表中

C# 使用C将外键插入带有SQL查询的表中,c#,sql,foreign-keys,sqlcommand,C#,Sql,Foreign Keys,Sqlcommand,我有一个数据库,有3个表标识、标识组和组 Identification_group表有两个外键列,Identification_id和group_id 在我的表格中,您可以选择组号,它会将正确的组id返回到标识组表中 是否可以编写一个SQL查询,使用表单中选择字段的最后一个标识和组标识,并将其写入标识组表 很抱歉格式错误,第一次在这里发布 提前感谢您您需要在最后执行SqlCommand,并可能使用数据读取器获得结果 例如: 私有静态void ReadOrderDatastring连接字符串 {

我有一个数据库,有3个表标识、标识组和组

Identification_group表有两个外键列,Identification_id和group_id

在我的表格中,您可以选择组号,它会将正确的组id返回到标识组表中

是否可以编写一个SQL查询,使用表单中选择字段的最后一个标识和组标识,并将其写入标识组表

很抱歉格式错误,第一次在这里发布


提前感谢您

您需要在最后执行SqlCommand,并可能使用数据读取器获得结果

例如:

私有静态void ReadOrderDatastring连接字符串 { 字符串查询字符串= 从dbo.Orders中选择OrderID、CustomerID;; 使用SqlConnection=newsqlconnection 连接字符串 { SqlCommand=newsqlcommand 查询串、连接; 连接。打开; 使用SqlDataReader=command.ExecuteReader { 边读边读 { Console.WriteLineString.Format{0},{1}, 读卡器[0],读卡器[1]; } } 连接。关闭; } } 请尝试以下方法:

您的SQL语句有一个问题,没有关闭括号。此外,在SQL语句中只需要@符号,而在C代码中不需要

// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (@fk_group_id, @fk_identification_id)";

// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);

// Open the SQL connection
myConnection.Open();

// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);

// Bind the command
schreiben.CommandText = query;

// Execute the command
schreiben.ExecuteNonQuery();

// Close the connection
myConnection.Close();

您只需使用schreiben.executenonqueryforgo执行命令即可添加它,立即更新我的代码。生产线的问题是schreiben.Parameters。AddWithValue@fk_identification_id,身份识别号;我想我需要使用类似lastSelectedId的东西,但我似乎无法让它工作。请从schreiben.Parameters中删除@符号。AddWithValue@fk_identification_id,身份验证_id;-在SQL查询语句中只需要@符号,而在实际的C代码中不需要。此外,SQL语句中没有右括号
// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (@fk_group_id, @fk_identification_id)";

// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);

// Open the SQL connection
myConnection.Open();

// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);

// Bind the command
schreiben.CommandText = query;

// Execute the command
schreiben.ExecuteNonQuery();

// Close the connection
myConnection.Close();