c# - 使用 C# 使用 SQL 查询将外键插入表中
问题描述
我有一个包含 3 个表的数据库Identification
,Identification_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();
抱歉格式不好,第一次在这里发帖。
先感谢您
解决方案
请尝试以下方法:
您的 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();
推荐阅读
- c# - Overriding classes in an EF Core data access layer
- azure - 如何使用 PowerShell 获取为 SQL Server 分配的 Azure Active Directory 管理员?
- javascript - Zendesk list endpoint is not working
- python - postgresql 10 on FreeBSD sporadically returns incorrect float values running the exact same query
- jquery - 将大量变量传递给 jQuery 中的函数
- reactjs - 在本机反应中设置状态值
- java - 我应该将 MongoDB 与实体的关系一起使用,以便在我的 Spring 5 项目中实现端到端的非阻塞吗?
- sql - 将字符串与 UNIQUEIDENTIFIER 进行比较?
- c# - 如何根据 AttributeID 字段获取动态控件类型
- c# - C# Interactive 可以显示计时信息吗?