繁体   English   中英

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

[英]Insert foreign key into table with SQL query using C#

我有一个包含 3 个表IdentificationIdentification_groupGroup的数据库。

Identification_group表有 2 个外键列, Identificaiton_idGroup_id

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

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

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

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

先感谢您

请尝试以下操作:

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

我有一个包含 3 个表IdentificationIdentification_groupGroup的数据库。

Identification_group表有 2 个外键列, Identificaiton_idGroup_id

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

是否可以编写使用最后一个Identification_idGroup_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();

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

先感谢您

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM