首页 > 解决方案 > 使用 C# 使用 SQL 查询将外键插入表中

问题描述

我有一个包含 3 个表的数据库IdentificationIdentification_group并且Group.

Identification_group表有 2 个外键列,Identificaiton_id并且Group_id.

在我的表单中,您可以选择组号,它将正确的 Group_id 返回到Identification_group表中。

是否可以编写一个使用 lastIdentification_id和 the Group_id(来自我表单中的选择字段)并将其写入Identification_group表的 SQL 查询?

string sqlquery1 = "Insert into [dbo].[identification_group] (fk_group_id,fk_identification_id values (@fk_group_id,@fk_identification_id;";
            SqlCommand schreiben = new SqlCommand(sqlquery1, myConnection);
            myConnection.Open();
            schreiben.Parameters.AddWithValue("@fk_identification_id", intidentification_id);
            schreiben.Parameters.AddWithValue("@fk_group_id", Wil_Jls_idComboBox.SelectedValue);
schreiben.CommandText = sqlquery;
schreiben.ExecuteNonQuery();
            myConnection.Close();

抱歉格式不好,第一次在这里发帖。

先感谢您

标签: c#sqlforeign-keyssqlcommand

解决方案


请尝试以下方法:

您的 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();

推荐阅读